<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');
require_once('source/restrict_admin.php'); 

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Function to generate random PINs (numeric only)
function generateRandomPIN($length = 10) {
    $pin = '';
    $characters = '0123456789';
    $charactersLength = strlen($characters);
    
    for ($i = 0; $i < $length; $i++) {
        $pin .= $characters[rand(0, $charactersLength - 1)];
    }
    
    return $pin;
}

// Function to check if batch name exists
function batchExists($batchName) {
    global $DBH;
    $stmt = $DBH->prepare("SELECT COUNT(*) FROM tbl_pin WHERE batch_id = ?");
    $stmt->execute([$batchName]);
    return $stmt->fetchColumn() > 0;
}

// Function to get next serial number for a batch
function getNextSerial($batchName) {
    global $DBH;
    $stmt = $DBH->prepare("SELECT MAX(Serial) FROM tbl_pin WHERE batch_id = ?");
    $stmt->execute([$batchName]);
    $maxSerial = $stmt->fetchColumn();
    return $maxSerial ? $maxSerial + 1 : 1;
}

// Handle PIN generation
if (isset($_POST['generate'])) {
    $quantity = (int)$_POST['quantity'];
    $batchName = trim($_POST['batch_name']);
    
    if ($quantity <= 0) {
        $_SESSION['error'] = "Quantity must be greater than 0";
    } elseif (empty($batchName)) {
        $_SESSION['error'] = "Batch name cannot be empty";
    } else {
        try {
            $DBH->beginTransaction();
            
            $nextSerial = getNextSerial($batchName);
            $stmt = $DBH->prepare("INSERT INTO tbl_pin (pin, Serial, batch_id, created_date_time) VALUES (?, ?, ?, NOW())");
            
            $generatedPins = [];
            for ($i = 0; $i < $quantity; $i++) {
                $pin = generateRandomPIN(10); // 10-digit numeric PIN
                $serial = $nextSerial + $i;
                $stmt->execute([$pin, $serial, $batchName]);
                $generatedPins[] = $pin;
            }
            
            $DBH->commit();
            $_SESSION['success'] = "Successfully generated $quantity PINs for batch '$batchName'";
        } catch (PDOException $e) {
            $DBH->rollBack();
            $_SESSION['error'] = "Error generating PINs: " . $e->getMessage();
        }
    }
    
    header("Location: post_pin.php");
    exit();
}

// Handle batch deletion
if (isset($_POST['delete_batch'])) {
    $batchName = $_POST['batch_name'];
    
    try {
        $DBH->beginTransaction();
        $stmt = $DBH->prepare("DELETE FROM tbl_pin WHERE batch_id = ?");
        $stmt->execute([$batchName]);
        $DBH->commit();
        $_SESSION['success'] = "Batch '$batchName' deleted successfully";
    } catch (PDOException $e) {
        $DBH->rollBack();
        $_SESSION['error'] = "Error deleting batch: " . $e->getMessage();
    }
    
    header("Location: post_pin.php");
    exit();
}

// Get all batches
$batches = sql($DBH, "SELECT batch_id, COUNT(*) as pin_count, MIN(created_date_time) as created_date 
                      FROM tbl_pin 
                      GROUP BY batch_id 
                      ORDER BY created_date DESC", [], "rows");

// Get pins for selected batch
$currentBatch = isset($_GET['batch']) ? $_GET['batch'] : null;
$pins = [];
if ($currentBatch) {
    $pins = sql($DBH, "SELECT * FROM tbl_pin WHERE batch_id = ? ORDER BY Serial", [$currentBatch], "rows");
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Verbum Dei - PIN Management</title>
    
    <!-- Bootstrap CSS -->
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <!-- Custom styles -->
    <link href="css/sb-admin.css" rel="stylesheet">
    
    <style>
        :root {
            --primary: #0d47a1;
            --secondary: #1976d2;
            --light: #e3f2fd;
        }
        
        .card {
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border: none;
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
            border-radius: 8px 8px 0 0 !important;
            padding: 15px 20px;
        }
        
        .btn-primary {
            background-color: var(--primary);
            border-color: var(--primary);
        }
        
        .btn-danger {
            background-color: #c62828;
            border-color: #c62828;
        }
        
        .badge-batch {
            background-color: var(--secondary);
            color: white;
            font-size: 0.8rem;
            padding: 5px 10px;
            border-radius: 20px;
        }
        
        .pin-card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            padding: 15px;
            margin-bottom: 15px;
            border-left: 4px solid var(--primary);
        }
        
        .pin-code {
            font-family: 'Courier New', monospace;
            font-size: 1.2rem;
            font-weight: bold;
            letter-spacing: 2px;
            color: #002171;
        }
        
        @media print {
            body * {
                visibility: hidden;
            }
            .print-section, .print-section * {
                visibility: visible;
            }
            .print-section {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
            }
            .no-print {
                display: none !important;
            }
        }
    </style>
</head>

<body class="fixed-nav sticky-footer bg-dark" id="page-top">
    <!-- Navigation -->
    <?php include('source/navbar.php'); ?>

    <div class="content-wrapper">
        <div class="container-fluid">
            <!-- Breadcrumbs -->
            <ol class="breadcrumb">
                <li class="breadcrumb-item">
                    <a href="index.php">Dashboard</a>
                </li>
                <li class="breadcrumb-item active">PIN Management</li>
            </ol>

            <!-- Messages -->
            <?php if (isset($_SESSION['error'])): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                </div>
            <?php endif; ?>
            
            <?php if (isset($_SESSION['success'])): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                </div>
            <?php endif; ?>

            <div class="row">
                <div class="col-lg-12">
                    <!-- Generate PINs Card -->
                    <div class="card mb-4 no-print">
                        <div class="card-header">
                            <i class="fa fa-key"></i> Generate New PIN Batch
                        </div>
                        <div class="card-body">
                            <form method="post" action="post_pin.php">
                                <div class="form-row">
                                    <div class="form-group col-md-6">
                                        <label for="batch_name">Batch Name</label>
                                        <input type="text" class="form-control" id="batch_name" name="batch_name" required 
                                               placeholder="e.g., First-Term-2023">
                                    </div>
                                    <div class="form-group col-md-4">
                                        <label for="quantity">Number of PINs</label>
                                        <select class="form-control" id="quantity" name="quantity" required>
                                            <option value="50">50</option>
                                            <option value="100">100</option>
                                            <option value="200">200</option>
                                            <option value="500">500</option>
                                            <option value="1000">1000</option>
                                        </select>
                                    </div>
                                    <div class="form-group col-md-2 d-flex align-items-end">
                                        <button type="submit" name="generate" class="btn btn-primary btn-block">
                                            <i class="fa fa-plus"></i> Generate
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Batches List Card -->
                    <div class="card mb-4 no-print">
                        <div class="card-header">
                            <i class="fa fa-list"></i> PIN Batches
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th>Batch Name</th>
                                            <th>PIN Count</th>
                                            <th>Created Date</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if ($batches && is_array($batches)): ?>
                                            <?php foreach ($batches as $batch): ?>
                                                <tr>
                                                    <td>
                                                        <a href="post_pin.php?batch=<?php echo urlencode($batch['batch_id']); ?>">
                                                            <?php echo htmlspecialchars($batch['batch_id']); ?>
                                                        </a>
                                                    </td>
                                                    <td><?php echo $batch['pin_count']; ?></td>
                                                    <td><?php echo date('M j, Y h:i A', strtotime($batch['created_date'])); ?></td>
                                                    <td>
                                                        <a href="post_pin.php?batch=<?php echo urlencode($batch['batch_id']); ?>" class="btn btn-sm btn-info">
                                                            <i class="fa fa-eye"></i> View
                                                        </a>
                                                        <form method="post" action="post_pin.php" style="display: inline;">
                                                            <input type="hidden" name="batch_name" value="<?php echo htmlspecialchars($batch['batch_id']); ?>">
                                                            <button type="submit" name="delete_batch" class="btn btn-sm btn-danger" 
                                                                    onclick="return confirm('Are you sure you want to delete this batch? This cannot be undone.');">
                                                                <i class="fa fa-trash"></i> Delete
                                                            </button>
                                                        </form>
                                                        <a href="print_batch.php?batch=<?php echo urlencode($batch['batch_id']); ?>" class="btn btn-sm btn-success">
                                                            <i class="fa fa-print"></i> Print
                                                        </a>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <tr>
                                                <td colspan="4" class="text-center">No batches found</td>
                                            </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- Current Batch Details -->
                    <?php if ($currentBatch): ?>
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <div>
                                    <i class="fa fa-key"></i> PIN Batch: <?php echo htmlspecialchars($currentBatch); ?>
                                </div>
                                <div>
                                    <span class="badge badge-pill badge-primary">
                                        <?php echo count($pins); ?> PINs
                                    </span>
                                    <a href="print_batch.php?batch=<?php echo urlencode($currentBatch); ?>" class="btn btn-sm btn-success ml-2" target="_blank">
                                        <i class="fa fa-print"></i> Print Batch
                                    </a>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <?php if ($pins && is_array($pins)): ?>
                                        <?php foreach ($pins as $pin): ?>
                                            <div class="col-md-4 mb-4">
                                                <div class="pin-card">
                                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                                        <span class="text-muted">Serial:</span>
                                                        <strong>R-<?php echo str_pad($pin['Serial'], 5, "0", STR_PAD_LEFT); ?></strong>
                                                    </div>
                                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                                        <span class="text-muted">PIN:</span>
                                                        <span class="pin-code"><?php echo chunk_split($pin['pin'], 4, '-'); ?></span>
                                                    </div>
                                                    <div class="text-center mt-3">
                                                        <small class="text-muted">Valid for <?php echo htmlspecialchars($currentBatch); ?></small>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div class="col-12">
                                            <p class="text-center">No PINs found for this batch</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Footer -->
        <footer class="sticky-footer bg-dark no-print">
            <div class="container">
                <div class="text-center">
                    <small>Copyright &copy; Verbum Dei <?php echo date('Y'); ?></small>
                </div>
            </div>
        </footer>
    </div>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    
    <!-- Custom scripts -->
    <script>
        $(document).ready(function() {
            // Auto-focus on batch name field
            $('#batch_name').focus();
        });
    </script>
</body>
</html>