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

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

// Get user details for permission checks
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
}

// Check if user has admin access
if ($role_id != 1) {
    $_SESSION['error_message'] = "You don't have permission to approve/reject deposits.";
    header('Location: deposit_list.php');
    exit();
}

// Check if deposit ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "No deposit ID provided.";
    header('Location: deposit_list.php');
    exit();
}

$deposit_id = intval($_GET['id']);

// Get deposit details
$sql = "SELECT 
            d.*,
            u1.full_name as created_by_name,
            u2.full_name as deposit_user_name,
            u3.full_name as approval_user_name
        FROM 
            deposits d
        LEFT JOIN 
            users u1 ON d.created_by = u1.user_id
        LEFT JOIN 
            users u2 ON d.deposit_user_id = u2.user_id
        LEFT JOIN 
            users u3 ON d.approval_user_id = u3.user_id
        WHERE 
            d.id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $deposit_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Deposit not found.";
    header('Location: deposit_list.php');
    exit();
}

$deposit = $result->fetch_assoc();

// Check if deposit is already processed
if ($deposit['status'] !== 'pending') {
    $_SESSION['error_message'] = "This deposit has already been " . $deposit['status'] . ".";
    header('Location: view_deposit.php?id=' . $deposit_id);
    exit();
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data
    $status = $_POST['status'];
    $comments = $_POST['comments'];
    
    // Validate input
    $errors = [];
    
    if (empty($status) || !in_array($status, ['approved', 'rejected'])) {
        $errors[] = "Status is required and must be either approved or rejected.";
    }
    
    if ($status === 'rejected' && empty($comments)) {
        $errors[] = "Comments are required when rejecting a deposit.";
    }
    
    // If no errors, update the record
    if (empty($errors)) {
        try {
            // Begin transaction
            $conn->begin_transaction();
            
            // Update deposit status
            $sql = "UPDATE deposits SET status = ?, comments = ? WHERE id = ?";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('ssi', $status, $comments, $deposit_id);
            
            if (!$stmt->execute()) {
                throw new Exception("Error updating deposit: " . $stmt->error);
            }
            
            // Commit the transaction
            $conn->commit();
            
            $_SESSION['success_message'] = "Deposit " . ucfirst($status) . " successfully.";
            header('Location: deposit_list.php');
            exit();
            
        } catch (Exception $e) {
            // Rollback transaction on error
            $conn->rollback();
            
            $error_message = $e->getMessage();
        }
    }
}

// Format date helper function
function formatDate($date) {
    return date('Y-m-d', strtotime($date));
}

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Royal Freight Management System";
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Approve Deposit')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Sweet Alert css -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    
    <style>
        .deposit-details-card {
            margin-bottom: 1.5rem;
        }
        .deposit-header {
            padding: 1rem;
            border-bottom: 1px solid #e9e9ef;
            background-color: #f8f9fa;
        }
        .detail-label {
            font-weight: 600;
            color: #495057;
            margin-bottom: 0.25rem;
        }
        .detail-value {
            margin-bottom: 1rem;
        }
        .form-label {
            font-weight: 500;
        }
        .required:after {
            content: " *";
            color: red;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Finance Management', 'title' => 'Approve/Reject Deposit')); ?>

                    <?php
                    // Show error message if set
                    if (isset($error_message)) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo $error_message;
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                    }
                    
                    // Show validation errors if any
                    if (!empty($errors)) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo '<ul class="mb-0">';
                        foreach ($errors as $error) {
                            echo '<li>' . $error . '</li>';
                        }
                        echo '</ul>';
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                    }
                    ?>

                    <div class="row">
                        <div class="col-lg-6">
                            <div class="card deposit-details-card">
                                <div class="card-header deposit-header">
                                    <h5 class="card-title mb-0">Deposit Details</h5>
                                </div>
                                <div class="card-body">
                                    <div class="detail-label">Deposit ID</div>
                                    <div class="detail-value"><?php echo $deposit_id; ?></div>
                                    
                                    <div class="detail-label">Deposit Date</div>
                                    <div class="detail-value"><?php echo formatDate($deposit['deposit_date']); ?></div>
                                    
                                    <div class="detail-label">Bank</div>
                                    <div class="detail-value"><?php echo $deposit['bank']; ?></div>
                                    
                                    <div class="detail-label">Currency</div>
                                    <div class="detail-value"><?php echo $deposit['currency']; ?></div>
                                    
                                    <div class="detail-label">Amount</div>
                                    <div class="detail-value"><?php echo number_format($deposit['amount'], 2); ?></div>
                                    
                                    <div class="detail-label">Purpose</div>
                                    <div class="detail-value">
                                        <?php echo nl2br(htmlspecialchars($deposit['purpose'])); ?>
                                    </div>
                                    
                                    <div class="detail-label">Created By</div>
                                    <div class="detail-value"><?php echo $deposit['created_by_name']; ?></div>
                                    
                                    <div class="detail-label">Deposit User</div>
                                    <div class="detail-value"><?php echo $deposit['deposit_user_name']; ?></div>
                                    
                                    <div class="detail-label">Approval User</div>
                                    <div class="detail-value"><?php echo $deposit['approval_user_name']; ?></div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-lg-6">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Approval Decision</h5>
                                </div>
                                <div class="card-body">
                                    <form method="POST" action="" id="approval-form">
                                        <div class="mb-3">
                                            <label class="form-label required">Approval Status</label>
                                            <div class="form-check mb-2">
                                                <input class="form-check-input" type="radio" name="status" id="status-approve" value="approved" checked>
                                                <label class="form-check-label" for="status-approve">
                                                    Approve Deposit
                                                </label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="status" id="status-reject" value="rejected">
                                                <label class="form-check-label" for="status-reject">
                                                    Reject Deposit
                                                </label>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="comments" class="form-label" id="comments-label">Comments</label>
                                            <textarea class="form-control" id="comments" name="comments" rows="4" placeholder="Enter comments or reason for rejection"></textarea>
                                            <div class="form-text" id="comments-help">Comments are required when rejecting a deposit.</div>
                                        </div>
                                        
                                        <div class="mb-3 text-end">
                                            <a href="view_deposit.php?id=<?php echo $deposit_id; ?>" class="btn btn-secondary me-2">Cancel</a>
                                            <button type="submit" class="btn btn-primary" id="submit-btn">Submit Decision</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Toggle required state of comments field based on status selection
            $('input[name="status"]').change(function() {
                const isRejected = $('#status-reject').is(':checked');
                
                if (isRejected) {
                    $('#comments-label').addClass('required');
                    $('#comments').attr('required', 'required');
                    $('#comments-help').show();
                } else {
                    $('#comments-label').removeClass('required');
                    $('#comments').removeAttr('required');
                    $('#comments-help').hide();
                }
            });
            
            // Trigger change event on page load to set initial state
            $('input[name="status"]:checked').trigger('change');
            
            // Form submission confirmation
            $('#approval-form').on('submit', function(e) {
                e.preventDefault();
                
                // Check if rejection without comments
                const isRejected = $('#status-reject').is(':checked');
                const comments = $('#comments').val().trim();
                
                if (isRejected && !comments) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Comments Required',
                        text: 'Please provide comments or reason for rejection.',
                        confirmButtonColor: '#3085d6'
                    });
                    return false;
                }
                
                const action = $('input[name="status"]:checked').val() === 'approved' ? 'approve' : 'reject';
                
                Swal.fire({
                    title: 'Confirm Decision',
                    text: `Are you sure you want to ${action} this deposit?`,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: `Yes, ${action} it!`
                }).then((result) => {
                    if (result.isConfirmed) {
                        this.submit();
                    }
                });
            });
        });
    </script>
</body>
</html>