<?php
include('header.php');
$fee = 30;
$fee_res = mysqli_query($conn, "SELECT fee_amount FROM fee_settings WHERE service_name='delhi_birth'");
if ($fee_res && mysqli_num_rows($fee_res) > 0) {
    $fee_row = mysqli_fetch_assoc($fee_res);
    $fee = $fee_row['fee_amount'];
}
$wallet = $_SESSION['walletamount'];

// Auto-generate Registration No: MCDOLIR-0126-XXXXXXX (auto increment)
$reg_prefix = 'MCDOLIR-0126-';
$reg_start = 1104990;
$last_reg = mysqli_query($conn, "SELECT registration_no FROM delhi_birth ORDER BY id DESC LIMIT 1");
if ($last_reg && mysqli_num_rows($last_reg) > 0) {
    $last_row = mysqli_fetch_assoc($last_reg);
    $last_num = intval(preg_replace('/^MCDOLIR-\d+-/', '', $last_row['registration_no']));
    $next_num = $last_num + 1;
} else {
    $next_num = $reg_start;
}
$auto_reg_no = $reg_prefix . $next_num;

// Certificate Statistics for Display
$stats_query = mysqli_query($conn, "SELECT COUNT(*) as total FROM delhi_birth");
$total_certificates = ($stats_query && mysqli_num_rows($stats_query) > 0) ? mysqli_fetch_assoc($stats_query)['total'] : 0;
$formatted_total = number_format($total_certificates);

if (isset($_POST['savedata'])) {
    if ($wallet < $fee) {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>";
        echo "<script>
            Swal.fire({ 
                title: 'Insufficient Wallet Balance!', 
                text: 'Your balance: ₹$wallet. Required: ₹$fee. Please add money to continue.', 
                icon: 'warning', 
                showCancelButton: true,
                confirmButtonText: 'Add Money',
                cancelButtonText: 'Cancel'
            }).then((result) => { 
                if (result.isConfirmed) { 
                    window.location.href = 'addwallet'; 
                } 
            });
        </script>";
        exit;
    }

    $registration_no = mysqli_real_escape_string($conn, trim($_POST['registration_no']));
    $name = mysqli_real_escape_string($conn, trim($_POST['name']));
    $gender = mysqli_real_escape_string($conn, trim($_POST['gender']));
    $date_of_birth = mysqli_real_escape_string($conn, trim($_POST['date_of_birth']));
    $place_of_birth = mysqli_real_escape_string($conn, trim($_POST['place_of_birth']));
    $date_of_registration = mysqli_real_escape_string($conn, trim($_POST['date_of_registration']));
    $father_name = mysqli_real_escape_string($conn, trim($_POST['father_name']));
    $mother_name = mysqli_real_escape_string($conn, trim($_POST['mother_name']));
    $present_address = mysqli_real_escape_string($conn, trim($_POST['present_address']));
    $permanent_address = mysqli_real_escape_string($conn, trim($_POST['permanent_address']));
    $date_of_issue = mysqli_real_escape_string($conn, trim($_POST['date_of_issue']));
    $userid = $_SESSION['phone'];
    $application_id = 'APP' . time() . rand(1000, 9999);

    if ($registration_no == "") {
        $msgno = 'Please enter registration number';
    } elseif ($name == "") {
        $msgno = 'Please enter full name';
    } elseif ($gender == "") {
        $msgno = 'Please select gender';
    } elseif ($date_of_birth == "") {
        $msgno = 'Please enter date of birth';
    } elseif ($place_of_birth == "") {
        $msgno = 'Please enter place of birth';
    } elseif ($father_name == "") {
        $msgno = 'Please enter father name';
    } elseif ($mother_name == "") {
        $msgno = 'Please enter mother name';
    } elseif ($present_address == "") {
        $msgno = 'Please enter present address';
    } elseif ($permanent_address == "") {
        $msgno = 'Please enter permanent address';
    } else {
        $query = "INSERT INTO `delhi_birth`
            (`registration_no`, `name`, `gender`, `date_of_birth`, `place_of_birth`, `date_of_registration`,
            `father_name`, `mother_name`, `present_address`, `permanent_address`, `date_of_issue`, `userid`, `application_id`, `status`, `created_at`)
            VALUES
            ('$registration_no', '$name', '$gender', '$date_of_birth', '$place_of_birth', '$date_of_registration',
            '$father_name', '$mother_name', '$present_address', '$permanent_address', '$date_of_issue', '$userid', '$application_id', 'approved', NOW())";

        $result = mysqli_query($conn, $query);

        if ($result) {
            mysqli_query($conn, "UPDATE usertable SET walletamount=walletamount-$fee WHERE phone='$userid'");
            $_SESSION['walletamount'] = $_SESSION['walletamount'] - $fee;
            ?>
            <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
            <script>
                Swal.fire({
                    title: 'Application Submitted Successfully!',
                    html: `
                        <div style="text-align: center;">
                            <div style="font-size: 48px; color: #10b981; margin: 20px 0;">✓</div>
                            <p><strong>Application ID:</strong> <?php echo $application_id; ?></p>
                            <p><strong>Registration No:</strong> <?php echo $auto_reg_no; ?></p>
                            <p style="color: #059669;">Your certificate is ready for download!</p>
                        </div>
                    `,
                    icon: 'success',
                    showCancelButton: true,
                    confirmButtonText: 'View Certificate',
                    cancelButtonText: 'Back to List'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.open('dehli_birth_pdf?reg_no=' + encodeURIComponent('<?php echo $auto_reg_no; ?>'), '_blank');
                    }
                    setTimeout(() => { window.location = 'dehli_birth_list'; }, 1000);
                });
            </script>
            <?php
        } else {
            $msgno = "Error saving data: " . mysqli_error($conn);
        }
    }
}

if (!empty($msgno)) {
    echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>";
    echo "<script>Swal.fire({ title: 'Validation Error', text: '$msgno', icon: 'error', confirmButtonText: 'OK' });</script>";
}
?>

<!-- Stats Banner -->
<div style="background: linear-gradient(135deg, #1e40af 0%, #1e3a8a 100%); color: white; padding: 20px 0; margin-bottom: 20px;">
    <div class="container">
        <div class="row text-center">
            <div class="col-md-3 col-6">
                <div style="font-size: 28px; font-weight: 800;"><?php echo $formatted_total; ?>+</div>
                <div style="font-size: 14px; opacity: 0.9;">Certificates Issued</div>
            </div>
            <div class="col-md-3 col-6">
                <div style="font-size: 28px; font-weight: 800;"><?php echo number_format(ceil($total_certificates * 0.85)); ?>+</div>
                <div style="font-size: 14px; opacity: 0.9;">Happy Citizens</div>
            </div>
            <div class="col-md-3 col-6">
                <div style="font-size: 28px; font-weight: 800;">24/7</div>
                <div style="font-size: 14px; opacity: 0.9;">Online Service</div>
            </div>
            <div class="col-md-3 col-6">
                <div style="font-size: 28px; font-weight: 800;">100%</div>
                <div style="font-size: 14px; opacity: 0.9;">Secure Process</div>
            </div>
        </div>
    </div>
</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<style>
.delhi-card {
    max-width: 950px;
    margin: 25px auto;
    background: linear-gradient(135deg, #ffffff 0%, #f0f4ff 100%);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0,0,0,0.12);
    overflow: hidden;
}
.delhi-header {
    background: linear-gradient(135deg, #00008B 0%, #1a3a8a 100%);
    color: #fff;
    padding: 20px 30px;
    display: flex;
    align-items: center;
    gap: 15px;
}
.delhi-header i { font-size: 28px; }
.delhi-header h4 { margin: 0; font-weight: 600; letter-spacing: 0.5px; }
.delhi-body { padding: 30px; }
.section-title {
    color: #00008B;
    font-weight: 700;
    margin-bottom: 18px;
    padding-bottom: 8px;
    border-bottom: 2px solid #e2e8f0;
}
.form-group { margin-bottom: 18px; }
.form-group label {
    font-weight: 600;
    color: #344767;
    font-size: 13px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 6px;
    display: block;
}
.form-group .form-control, .form-group select, .form-group textarea {
    border: 2px solid #e2e8f0;
    border-radius: 10px;
    padding: 10px 14px;
    font-size: 14px;
    transition: all 0.3s ease;
    background: #fff;
    width: 100%;
}
.form-group .form-control:focus, .form-group select:focus, .form-group textarea:focus {
    border-color: #00008B;
    box-shadow: 0 0 0 3px rgba(0,0,139,0.15);
    outline: none;
}
.input-icon { position: relative; }
.input-icon i {
    position: absolute; right: 14px; top: 50%; transform: translateY(-50%);
    color: #94a3b8; pointer-events: none;
}
.input-icon .form-control { padding-right: 40px; }
.fee-badge {
    background: linear-gradient(135deg, #ff9a00 0%, #ff6b00 100%);
    color: #fff;
    padding: 10px 20px;
    border-radius: 10px;
    font-weight: 700;
    font-size: 16px;
    display: inline-block;
}
.btn-submit {
    background: linear-gradient(135deg, #00008B 0%, #1a3a8a 100%);
    color: #fff;
    border: none;
    padding: 12px 40px;
    border-radius: 10px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
}
.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0,0,139,0.4);
    color: #fff;
}
.btn-cancel {
    background: #dc3545;
    color: #fff;
    border: none;
    padding: 12px 30px;
    border-radius: 10px;
    font-size: 16px;
    font-weight: 600;
    text-decoration: none;
    transition: all 0.3s ease;
}
.btn-cancel:hover { transform: translateY(-2px); color: #fff; text-decoration: none; }
.copy-btn {
    background: #6c757d;
    color: #fff;
    border: none;
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 11px;
    cursor: pointer;
    margin-left: 8px;
}
</style>

<div class="delhi-card">
    <div class="delhi-header">
        <i class="fas fa-baby"></i>
        <div>
            <h4>Delhi Birth Certificate - Online Application</h4>
            <small style="opacity:0.8;">Municipal Corporation of Delhi - Fast, Easy and Secure Digital Process</small>
        </div>
    </div>
    <div class="delhi-body">
        <!-- Process Steps -->
        <div class="row" style="margin-bottom: 25px;">
            <div class="col-12">
                <div style="background: #f8fafc; border-radius: 12px; padding: 20px;">
                    <h6 style="margin-bottom: 15px; color: #1e3a8a; text-align: center;"><i class="fas fa-route"></i> Simple 4-Step Process</h6>
                    <div class="row text-center">
                        <div class="col-md-3">
                            <div style="background: #10b981; color: white; width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 10px; font-weight: bold;">1</div>
                            <div style="font-weight: 600; color: #374151;">Fill Form</div>
                        </div>
                        <div class="col-md-3">
                            <div style="background: #3b82f6; color: white; width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 10px; font-weight: bold;">2</div>
                            <div style="font-weight: 600; color: #374151;">Pay Fee</div>
                        </div>
                        <div class="col-md-3">
                            <div style="background: #8b5cf6; color: white; width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 10px; font-weight: bold;">3</div>
                            <div style="font-weight: 600; color: #374151;">Auto Approval</div>
                        </div>
                        <div class="col-md-3">
                            <div style="background: #f59e0b; color: white; width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 10px; font-weight: bold;">4</div>
                            <div style="font-weight: 600; color: #374151;">Download PDF</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <form method="post" autocomplete="off" action="" onsubmit="return validateForm()">

            <!-- Section 1: Registration Details -->
            <h6 class="section-title"><i class="fas fa-file-alt"></i> Registration Details</h6>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-hashtag"></i> Registration No (Auto)</label>
                        <div class="input-icon">
                            <input class="form-control" name="registration_no" type="text" required value="<?php echo $auto_reg_no; ?>" readonly style="background:#f0f4ff; font-weight:700; color:#00008B;">
                            <i class="fas fa-hashtag"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-calendar-check"></i> Date of Registration</label>
                        <div class="input-icon">
                            <input class="form-control" name="date_of_registration" id="reg_date_picker" type="text" required placeholder="Select Date" readonly>
                            <i class="fas fa-calendar-alt"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-clock"></i> Date of Issue</label>
                        <div class="input-icon">
                            <input class="form-control" name="date_of_issue" id="issue_date_picker" type="text" required placeholder="Select Date & Time" readonly>
                            <i class="fas fa-clock"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-map-marker-alt"></i> Place of Birth</label>
                        <div class="input-icon">
                            <input class="form-control" name="place_of_birth" type="text" required placeholder="e.g. DR ANITAS GYNAE CENTRE A-3/129 PASCHIM VIHAR">
                            <i class="fas fa-hospital"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Section 2: Personal Details -->
            <h6 class="section-title" style="margin-top:10px;"><i class="fas fa-user"></i> Personal Details</h6>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-user"></i> Full Name</label>
                        <div class="input-icon">
                            <input class="form-control" name="name" id="child_name" type="text" required placeholder="e.g. RABBI NOOR">
                            <i class="fas fa-user"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-venus-mars"></i> Gender</label>
                        <select class="form-control" name="gender" required>
                            <option value="">-- Select Gender --</option>
                            <option value="MALE">Male</option>
                            <option value="FEMALE">Female</option>
                            <option value="OTHER">Other</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-calendar-alt"></i> Date of Birth</label>
                        <div class="input-icon">
                            <input class="form-control" name="date_of_birth" id="dob_picker" type="text" required placeholder="Select DOB" readonly>
                            <i class="fas fa-calendar-alt"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-male"></i> Father's Name</label>
                        <div class="input-icon">
                            <input class="form-control" name="father_name" type="text" required placeholder="e.g. MUSTAFA">
                            <i class="fas fa-male"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-female"></i> Mother's Name</label>
                        <div class="input-icon">
                            <input class="form-control" name="mother_name" type="text" required placeholder="e.g. MEENA">
                            <i class="fas fa-female"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Section 3: Address Details -->
            <h6 class="section-title" style="margin-top:10px;"><i class="fas fa-map-marker-alt"></i> Address Details</h6>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-home"></i> Present Address (at time of Birth)</label>
                        <textarea class="form-control" name="present_address" id="present_addr" rows="2" required placeholder="Enter complete present address"></textarea>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-map"></i> Permanent Address <button type="button" class="copy-btn" onclick="copyAddress()"><i class="fas fa-copy"></i> Same as Present</button></label>
                        <textarea class="form-control" name="permanent_address" id="permanent_addr" rows="2" required placeholder="Enter complete permanent address"></textarea>
                    </div>
                </div>
            </div>

            <!-- Wallet & Fee -->
            <div class="row">
                <div class="col-12">
                    <div style="background:#fffbeb; border:2px solid #fbbf24; border-radius:10px; padding:12px; margin-top:5px; text-align:center;">
                        <small style="color:#92400e; font-weight:600;">WALLET BALANCE</small>
                        <h5 style="color:#047857; margin:4px 0; font-weight:800;">&#8377;<?php echo $_SESSION['walletamount']; ?></h5>
                    </div>
                </div>
                <div class="col-12" style="margin-top:15px;">
                    <hr style="border-color:#e2e8f0;">
                    <div class="d-flex justify-content-between align-items-center flex-wrap" style="gap:15px;">
                        <div style="display: flex; align-items: center; gap: 15px;">
                            <div class="fee-badge">
                                <i class="fas fa-wallet"></i> Fee: &#8377;<?php echo $fee; ?>
                            </div>
                            <div style="font-size: 14px; color: #059669; font-weight: 600;">
                                <i class="fas fa-check-circle"></i> Instant Download Available
                            </div>
                        </div>
                        <div style="display:flex; gap:10px; flex-wrap:wrap;">
                            <a href="dehli_birth_list" class="btn-cancel">
                                <i class="fas fa-times"></i> Cancel
                            </a>
                            <button type="submit" name="savedata" class="btn-submit" id="submitBtn">
                                <i class="fas fa-paper-plane"></i> Submit & Generate Certificate
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
function copyAddress() {
    document.getElementById('permanent_addr').value = document.getElementById('present_addr').value;
    Swal.fire({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 2000,
        icon: 'success',
        title: 'Address copied successfully!'
    });
}

// Form validation
document.querySelector('form').addEventListener('submit', function(e) {
    const wallet = <?php echo $wallet; ?>;
    const fee = <?php echo $fee; ?>;
    
    if (wallet < fee) {
        e.preventDefault();
        Swal.fire({
            title: 'Insufficient Balance!',
            text: `Your wallet balance is ₹${wallet}. Minimum ₹${fee} required.`,
            icon: 'error',
            showCancelButton: true,
            confirmButtonText: 'Add Money',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'addwallet';
            }
        });
        return false;
    }
    
    // Show loading during submission
    document.getElementById('submitBtn').innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    document.getElementById('submitBtn').disabled = true;
});

flatpickr("#dob_picker", { dateFormat: "Y-m-d", maxDate: "today", allowInput: false, disableMobile: true });
flatpickr("#reg_date_picker", { dateFormat: "Y-m-d", allowInput: false, disableMobile: true });
flatpickr("#issue_date_picker", { dateFormat: "Y-m-d H:i", enableTime: true, time_24hr: true, allowInput: false, disableMobile: true });
</script>

<script src="plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="dist/js/adminlte.js"></script>
</body>
</html>
