<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get corporate ID from URL
$corp_id = $_GET['id'] ?? null;
if (!$corp_id) {
    header('Location: corporate_list.php');
    exit();
}

// Fetch corporate details
$sql = "SELECT * FROM corporate WHERE corp_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $corp_id);
$stmt->execute();
$result = $stmt->get_result();
$corporate = $result->fetch_assoc();

if (!$corporate) {
    header('Location: corporate_list.php');
    exit();
}

// Fetch insurers for dropdown
$sql_insurers = "SELECT code, insurer FROM insurer ORDER BY insurer";
$result_insurers = $conn->query($sql_insurers);
$insurers = $result_insurers->fetch_all(MYSQLI_ASSOC);

?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Corporate')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Corporates', 'title' => 'Edit Corporate')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Edit Corporate Details</h4>
                                </div>
                                
                                <div class="card-body">
                                    <form id="editCorporateForm" method="POST">
                                        <input type="hidden" name="corp_id" value="<?php echo $corporate['corp_id']; ?>">
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label class="form-label">Corporate Name</label>
                                                <input type="text" class="form-control" name="corporate" 
                                                       value="<?php echo htmlspecialchars($corporate['corporate']); ?>" required>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Scheme Code</label>
                                                <input type="text" class="form-control" name="scheme" 
                                                       value="<?php echo htmlspecialchars($corporate['scheme']); ?>" required>
                                            </div>
                                        </div>

                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label class="form-label">Telephone</label>
                                                <input type="tel" class="form-control" name="tel_no" 
                                                       value="<?php echo htmlspecialchars($corporate['tel_no']); ?>">
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Mobile</label>
                                                <input type="tel" class="form-control" name="mobile_no" 
                                                       value="<?php echo htmlspecialchars($corporate['mobile_no']); ?>">
                                            </div>
                                        </div>

                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label class="form-label">Email</label>
                                                <input type="email" class="form-control" name="email" 
                                                       value="<?php echo htmlspecialchars($corporate['email']); ?>">
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Postal Address</label>
                                                <input type="text" class="form-control" name="postal_add" 
                                                       value="<?php echo htmlspecialchars($corporate['postal_add']); ?>">
                                            </div>
                                        </div>

                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label class="form-label">Physical Location</label>
                                                <input type="text" class="form-control" name="phy_loc" 
                                                       value="<?php echo htmlspecialchars($corporate['phy_loc']); ?>">
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">PIN Number</label>
                                                <input type="text" class="form-control" name="corp_pin" 
                                                       value="<?php echo htmlspecialchars($corporate['corp_pin']); ?>">
                                            </div>
                                        </div>

                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label class="form-label">Insurer</label>
                                                <select class="form-select" name="insurer">
                                                    <option value="">Select Insurer</option>
                                                    <?php foreach ($insurers as $insurer): ?>
                                                        <option value="<?php echo $insurer['code']; ?>" 
                                                                <?php echo $corporate['insurer'] == $insurer['code'] ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($insurer['insurer']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Policy Number</label>
                                                <input type="text" class="form-control" name="policy_no" 
                                                       value="<?php echo htmlspecialchars($corporate['policy_no']); ?>">
                                            </div>
                                        </div>

                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label class="form-label">Inpatient Threshold (%)</label>
                                                <input type="number" class="form-control" name="inpatient_threshold" 
                                                       value="<?php echo $corporate['inpatient_threshold']; ?>" 
                                                       min="0" max="100" step="0.01">
                                            </div>
                                            <div class="col-md-4">
                                                <label class="form-label">Outpatient Threshold (%)</label>
                                                <input type="number" class="form-control" name="outpatient_threshold" 
                                                       value="<?php echo $corporate['outpatient_threshold']; ?>" 
                                                       min="0" max="100" step="0.01">
                                            </div>
                                            <div class="col-md-4">
                                                <label class="form-label">Currency</label>
                                                <input type="text" class="form-control" name="currency" 
                                                       value="<?php echo htmlspecialchars($corporate['currency']); ?>">
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-12">
                                                <div class="text-end">
                                                    <a href="all_corporates.php" class="btn btn-light me-2">Cancel</a>
                                                    <button type="submit" class="btn btn-primary">Save Changes</button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

    <script>
        document.getElementById('editCorporateForm').addEventListener('submit', function(e) {
            e.preventDefault();

            // Show loading state
            Swal.fire({
                title: 'Saving...',
                text: 'Please wait while we update the corporate details',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            // Submit form using fetch
            fetch('update_corporate.php', {
                method: 'POST',
                body: new FormData(this)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: data.message,
                        confirmButtonText: 'OK'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = 'all_corporates.php';
                        }
                    });
                } else {
                    throw new Error(data.message || 'Failed to update corporate details');
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: error.message
                });
            });
        });
    </script>
</body>
</html>