<?php
/**
 * Enterprise HRM ERP System - Edit Resigned & Abscondee Record
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

$pageTitle = 'Edit Resigned & Abscondee';
$currentModule = 'exit';

$siteId = getCurrentSiteId();
$exitId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$selectedMonth = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

if ($exitId <= 0) {
    redirect(BASE_URL . '/modules/exit/resigned_abscondee_report.php', 'Invalid record ID.', 'error');
}

$errors = [];
$entry = null;

// Load entry
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM resigned_abscondee WHERE exit_id = ? AND site_id = ?");
    $stmt->execute([$exitId, $siteId]);
    $entry = $stmt->fetch();
    
    if (!$entry) {
        redirect(BASE_URL . '/modules/exit/resigned_abscondee_report.php', 'Record not found.', 'error');
    }
} catch (Exception $e) {
    error_log("Error loading entry: " . $e->getMessage());
    redirect(BASE_URL . '/modules/exit/resigned_abscondee_report.php', 'Error loading record.', 'error');
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_data'])) {
    try {
        $db = getDB();
        $db->beginTransaction();
        
        $empId = sanitize($_POST['emp_id'] ?? '');
        $name = sanitize($_POST['name'] ?? '');
        $designation = sanitize($_POST['designation'] ?? '');
        $category = sanitize($_POST['category'] ?? '');
        $resignedAbscondee = sanitize($_POST['resigned_abscondee'] ?? 'Resigned');
        $siteName = sanitize($_POST['site_name'] ?? '');
        $location = sanitize($_POST['location'] ?? '');
        $lastDateOfWorking = $_POST['last_date_of_working'] ?? null;
        $resignationSubmitted = $_POST['resignation_submitted'] ?? null;
        $noticePeriodServed = sanitize($_POST['notice_period_served'] ?? '');
        $remark = sanitize($_POST['remark'] ?? '');
        
        // Try to find employee_id
        $employeeId = null;
        if (!empty($empId)) {
            $stmt = $db->prepare("SELECT employee_id FROM employees WHERE employee_code = ? AND site_id = ? LIMIT 1");
            $stmt->execute([$empId, $siteId]);
            $emp = $stmt->fetch();
            if ($emp) {
                $employeeId = $emp['employee_id'];
            }
        }
        
        // Update record
        $stmt = $db->prepare("
            UPDATE resigned_abscondee SET
                employee_id = ?,
                emp_id = ?,
                name = ?,
                designation = ?,
                category = ?,
                resigned_abscondee = ?,
                site_name = ?,
                location = ?,
                last_date_of_working = ?,
                resignation_submitted = ?,
                notice_period_served = ?,
                remark = ?,
                updated_at = NOW()
            WHERE exit_id = ? AND site_id = ?
        ");
        $stmt->execute([
            $employeeId,
            $empId,
            $name,
            $designation,
            $category,
            $resignedAbscondee,
            $siteName,
            $location,
            $lastDateOfWorking ?: null,
            $resignationSubmitted ?: null,
            $noticePeriodServed,
            $remark,
            $exitId,
            $siteId
        ]);
        
        $db->commit();
        
        logAudit('UPDATE', 'resigned_abscondee', $exitId);
        
        redirect(BASE_URL . '/modules/exit/resigned_abscondee_report.php?month=' . $selectedMonth . '&year=' . $selectedYear, 'Record updated successfully.');
        
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        $errors[] = $e->getMessage();
        error_log("Error updating entry: " . $e->getMessage());
    }
}

// Get categories
$categories = ['Unskilled', 'Semi-Skilled', 'Skilled', 'Highly Skilled'];

// Get designations
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT DISTINCT designation_name FROM designations WHERE site_id = ? AND designation_status = 'active' ORDER BY designation_name");
    $stmt->execute([$siteId]);
    $designations = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Get site name
    $stmt = $db->prepare("SELECT site_name FROM sites WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $site = $stmt->fetch();
    $defaultSiteName = $site['site_name'] ?? '';
} catch (Exception $e) {
    error_log("Error loading data: " . $e->getMessage());
    $designations = [];
    $defaultSiteName = '';
}

include __DIR__ . '/../../includes/header.php';
include __DIR__ . '/../payroll/_navigation.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Edit Resigned & Abscondee Record</h2>
        <a href="<?php echo BASE_URL; ?>/modules/exit/resigned_abscondee_report.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" class="btn btn-secondary">← Back to Report</a>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="margin: 20px;">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <form method="POST" style="margin-top: 20px;">
        <input type="hidden" name="update_data" value="1">
        
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <div class="form-group">
                <label class="form-label" for="emp_id">Emp Id</label>
                <input type="text" id="emp_id" name="emp_id" class="form-control"
                       value="<?php echo htmlspecialchars($entry['emp_id'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="name">Name *</label>
                <input type="text" id="name" name="name" class="form-control" required
                       value="<?php echo htmlspecialchars($entry['name'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="designation">Designation</label>
                <input type="text" id="designation" name="designation" class="form-control" list="designation-list"
                       value="<?php echo htmlspecialchars($entry['designation'] ?? ''); ?>">
                <datalist id="designation-list">
                    <?php foreach ($designations as $des): ?>
                    <option value="<?php echo htmlspecialchars($des); ?>">
                    <?php endforeach; ?>
                </datalist>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="category">Category</label>
                <select id="category" name="category" class="form-control">
                    <option value="">Select</option>
                    <?php foreach ($categories as $cat): ?>
                    <option value="<?php echo htmlspecialchars($cat); ?>" 
                            <?php echo ($entry['category'] ?? '') === $cat ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($cat); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="resigned_abscondee">Resigned/ Abscondee</label>
                <select id="resigned_abscondee" name="resigned_abscondee" class="form-control">
                    <option value="Resigned" <?php echo ($entry['resigned_abscondee'] ?? 'Resigned') === 'Resigned' ? 'selected' : ''; ?>>Resigned</option>
                    <option value="Abscondee" <?php echo ($entry['resigned_abscondee'] ?? '') === 'Abscondee' ? 'selected' : ''; ?>>Abscondee</option>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="site_name">Site Name</label>
                <input type="text" id="site_name" name="site_name" class="form-control"
                       value="<?php echo htmlspecialchars($entry['site_name'] ?: $defaultSiteName); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="location">Location</label>
                <input type="text" id="location" name="location" class="form-control"
                       value="<?php echo htmlspecialchars($entry['location'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="last_date_of_working">Last Date of Working</label>
                <input type="date" id="last_date_of_working" name="last_date_of_working" class="form-control"
                       value="<?php echo htmlspecialchars($entry['last_date_of_working'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="resignation_submitted">Resignation Submitted</label>
                <input type="date" id="resignation_submitted" name="resignation_submitted" class="form-control"
                       value="<?php echo htmlspecialchars($entry['resignation_submitted'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="notice_period_served">Notice Period served</label>
                <input type="text" id="notice_period_served" name="notice_period_served" class="form-control"
                       value="<?php echo htmlspecialchars($entry['notice_period_served'] ?? ''); ?>"
                       placeholder="e.g., Yes/No">
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <label class="form-label" for="remark">Remarks</label>
                <textarea id="remark" name="remark" class="form-control" rows="3"
                          placeholder="Remarks"><?php echo htmlspecialchars($entry['remark'] ?? ''); ?></textarea>
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right; padding-top: 20px; border-top: 1px solid var(--border-color);">
            <a href="<?php echo BASE_URL; ?>/modules/exit/resigned_abscondee_report.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Update Record</button>
        </div>
    </form>
</div>

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

