<?php
require_once '../includes/functions.php';
requireLogin();

$user_id = $_SESSION['user_id'];
$settings = getSettings($pdo);
$cost = $settings['certificate_charge'];
$balance = $_SESSION['balance'];

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $is_admin_bypass = isAdmin();
    if (!$is_admin_bypass && $balance < $cost) {
        $error = "Insufficient wallet balance. Please recharge.";
    } else {
        // Collect Data
        $reg_no = $_POST['reg_no'];
        $name = $_POST['name'];
        $gender = $_POST['gender'];
        $dob = $_POST['dob'];
        $place = $_POST['place'];
        $date_reg = $_POST['date_reg'];
        $mother = $_POST['mother'];
        $father = $_POST['father'];
        $present_address = $_POST['present_address'];
        $permanent_address = $_POST['permanent_address'];
        $issue_date = $_POST['issue_date']; // User provided datetime

        // Generate Token
        $token = bin2hex(random_bytes(16));
        $hash = hash('sha256', $token . $reg_no); // Secure hash for QR

        // Deduct Balance
        $pdo->beginTransaction();
        try {
            // Check for duplicate Reg No
            $check = $pdo->prepare("SELECT id FROM certificates WHERE registration_no = ?");
            $check->execute([$reg_no]);
            if ($check->rowCount() > 0) {
                throw new Exception("Registration Number already exists.");
            }

            $deduct = $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
            $deduct->execute([$cost, $user_id]);

            // Save Certificate
            $sql = "INSERT INTO certificates (user_id, registration_no, name, gender, dob, place_of_birth, date_of_registration, mother_name, father_name, present_address, permanent_address, date_of_issue, token, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$user_id, $reg_no, $name, $gender, $dob, $place, $date_reg, $mother, $father, $present_address, $permanent_address, $issue_date, $token]);
            
            $cert_id = $pdo->lastInsertId();
            $pdo->commit();
            
            // Generate PDF (Redirect or call function)
            // For now, redirect to list
            $_SESSION['balance'] -= $cost;
            header("Location: my_certificates.php?new=" . $cert_id);
            exit();

        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Error: " . $e->getMessage();
        }
    }
}

// Default values
$generated_reg_no = generateRegistrationNumber(); // "MCDOLIR-..."
$default_issue_time = date('Y-m-d H:i:s');

include '../includes/header.php';
?>

<div class="row justify-content-center animate-fade-in">
    <div class="col-md-10">
        <div class="mb-4">
            <h2 class="fw-bold"><i class="fas fa-file-circle-plus text-primary me-2"></i> New <span class="text-primary">Application</span></h2>
            <p class="text-muted">Fill in the details below to generate your official certificate.</p>
        </div>

        <div class="glass-card p-5 bg-white">
            <div class="row mb-5">
                <div class="col-md-6 border-end">
                    <div class="p-3 bg-light rounded-4">
                        <small class="text-muted text-uppercase fw-bold tracking-wider">Application Fee</small>
                        <h3 class="fw-bold mb-0 text-primary">₹<?php echo $cost; ?></h3>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="p-3 bg-light rounded-4">
                        <small class="text-muted text-uppercase fw-bold tracking-wider">Your Balance</small>
                        <h3 class="fw-bold mb-0 <?php echo $balance < $cost ? 'text-danger' : 'text-success'; ?>">₹<?php echo number_format($balance, 2); ?></h3>
                    </div>
                </div>
            </div>
            
            <?php if ($error): ?>
                <div class="alert alert-danger border-0 rounded-3 mb-4"><i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?></div>
            <?php endif; ?>

            <?php if ($balance < $cost && !isAdmin()): ?>
                <div class="alert alert-warning border-0 rounded-4 p-4 d-flex align-items-center mb-4">
                    <i class="fas fa-wallet fa-2x me-3"></i>
                    <div>
                        <h6 class="fw-bold mb-1">Insufficient Balance</h6>
                        <p class="mb-0 small opacity-75">You need ₹<?php echo $cost; ?> to apply. <a href="my_wallet.php" class="fw-bold">Top up your wallet now</a></p>
                    </div>
                </div>
            <?php else: ?>

            <form method="POST">
                <div class="form-section mb-5">
                    <h5 class="fw-bold border-bottom pb-2 mb-4 text-secondary"><i class="fas fa-id-card me-2"></i> Registration Details</h5>
                    <div class="row">
                        <div class="col-md-6 mb-4">
                            <label class="form-label fw-semibold small">Registration No / पंजीकरण संख्या</label>
                            <input type="text" name="reg_no" class="form-control form-control-lg bg-light" value="<?php echo $generated_reg_no; ?>" required>
                        </div>
                        <div class="col-md-6 mb-4">
                            <label class="form-label fw-semibold small">Date of Registration / पंजीकरण की तिथि</label>
                            <input type="date" name="date_reg" class="form-control form-control-lg bg-light" required>
                        </div>
                    </div>
                </div>

                <div class="form-section mb-5">
                    <h5 class="fw-bold border-bottom pb-2 mb-4 text-secondary"><i class="fas fa-user me-2"></i> Personal Information</h5>
                    <div class="row">
                        <div class="col-md-8 mb-4">
                            <label class="form-label fw-semibold small">Full Name / नाम</label>
                            <input type="text" name="name" class="form-control form-control-lg bg-light" placeholder="e.g. Ramesh Kumar / रमेश कुमार" required>
                        </div>
                        <div class="col-md-4 mb-4">
                            <label class="form-label fw-semibold small">Gender / लिंग</label>
                            <select name="gender" class="form-select form-select-lg bg-light" required>
                                <option value="Male / पुरुष">Male / पुरुष</option>
                                <option value="Female / महिला">Female / महिला</option>
                                <option value="Transgender / ट्रांसजेंडर">Transgender / ट्रांसजेंडर</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-4">
                            <label class="form-label fw-semibold small">Date of Birth / जन्म की तिथि</label>
                            <input type="date" name="dob" class="form-control form-control-lg bg-light" required>
                        </div>
                        <div class="col-md-6 mb-4">
                            <label class="form-label fw-semibold small">Place of Birth / जन्म का स्थान</label>
                            <input type="text" name="place" class="form-control form-control-lg bg-light" required>
                        </div>
                    </div>
                </div>

                <div class="form-section mb-5">
                    <h5 class="fw-bold border-bottom pb-2 mb-4 text-secondary"><i class="fas fa-users-line me-2"></i> Parent Details</h5>
                    <div class="row">
                        <div class="col-md-6 mb-4">
                            <label class="form-label fw-semibold small">Mother's Name / माता का नाम</label>
                            <input type="text" name="mother" class="form-control form-control-lg bg-light" required>
                        </div>
                        <div class="col-md-6 mb-4">
                            <label class="form-label fw-semibold small">Father's Name / पिता का नाम</label>
                            <input type="text" name="father" class="form-control form-control-lg bg-light" required>
                        </div>
                    </div>
                </div>

                <div class="form-section mb-5">
                    <h5 class="fw-bold border-bottom pb-2 mb-4 text-secondary"><i class="fas fa-map-location-dot me-2"></i> Address Details</h5>
                    <div class="mb-4">
                        <label class="form-label fw-semibold small">Present Address / वर्तमान पता</label>
                        <textarea name="present_address" class="form-control bg-light" rows="3" required></textarea>
                    </div>
                    <div class="mb-4">
                        <label class="form-label fw-semibold small">Permanent Address / स्थाई पता</label>
                        <textarea name="permanent_address" class="form-control bg-light" rows="3" required></textarea>
                    </div>
                </div>

                <div class="form-section mb-5">
                    <h5 class="fw-bold border-bottom pb-2 mb-4 text-secondary"><i class="fas fa-calendar-check me-2"></i> Issuance</h5>
                    <div class="mb-4">
                        <label class="form-label fw-semibold small">Date of Issue / जारी करने की तिथि</label>
                        <input type="datetime-local" name="issue_date" class="form-control form-control-lg bg-light" value="<?php echo date('Y-m-d\TH:i:s'); ?>" required>
                    </div>
                </div>

                <button type="submit" class="btn btn-premium btn-lg w-100 py-3 shadow-lg">
                    <i class="fas fa-check-circle me-2"></i> Submit & Generate Certificate
                </button>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include '../includes/footer.php'; ?>
