<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

session_start();
require_once("../config/config.php");

$search = trim($_GET['search'] ?? '');

// Handle Delete
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    
    mysqli_begin_transaction($conn);
    try {
        $conn->query("DELETE FROM planning_budget WHERE planning_id = $id");
        $conn->query("DELETE FROM planning_schedule WHERE planning_id = $id");
        $conn->query("DELETE FROM planning_master WHERE id = $id");
        
        mysqli_commit($conn);
        $success = "Planning record deleted successfully!";
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $error = "Error deleting record: " . $e->getMessage();
    }
}

// Build Query with Search
$query = "SELECT p.id, p.project_id, p.created_at, p.updated_at, 
                 pr.project_name, pr.project_code,
                 (SELECT COUNT(*) FROM planning_budget WHERE planning_id = p.id) as item_count,
                 (SELECT COUNT(*) FROM planning_schedule WHERE planning_id = p.id) as milestone_count
          FROM planning_master p
          JOIN project_master pr ON p.project_id = pr.id";

if (!empty($search)) {
    $search_term = "%" . $conn->real_escape_string($search) . "%";
    $query .= " WHERE pr.project_name LIKE ? OR pr.project_code LIKE ?";
}

$query .= " ORDER BY p.created_at DESC";

$stmt = $conn->prepare($query);

if (!empty($search)) {
    $stmt->bind_param("ss", $search_term, $search_term);
}

$stmt->execute();
$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Planning List</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
    :root {
        --primary: #a855f7;
        --accent: #c084fc;
        --glass: rgba(255, 255, 255, 0.10);
        --glass-border: rgba(255, 255, 255, 0.20);
    }
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
        font-family: 'Inter', system-ui, sans-serif;
        min-height: 100vh;
        background: linear-gradient(135deg, rgba(0,0,0,0.78), rgba(0,0,0,0.92)), url('../background.jpeg') center/cover no-repeat fixed;
        color: #f1f5f9;
        padding: 20px;
    }
    .glass-container {
        max-width: 1400px;
        margin: 0 auto;
        background: var(--glass);
        backdrop-filter: blur(24px);
        border-radius: 32px;
        border: 1px solid var(--glass-border);
        box-shadow: 0 25px 80px rgba(0,0,0,0.65);
        overflow: hidden;
    }
    .header {
        background: linear-gradient(90deg, rgba(168,85,247,0.35), rgba(147,51,234,0.25));
        padding: 50px 40px;
        text-align: center;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 15px;
    }
    .header h1 {
        font-size: clamp(28px, 5vw, 42px);
        font-weight: 700;
        background: linear-gradient(to right, #e0bbff, #c084fc);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    .form-area { padding: 40px; }

    /* Search Box */
    .search-box {
        display: flex;
        gap: 10px;
        margin-bottom: 25px;
        max-width: 500px;
    }
    .search-box input {
        flex: 1;
        padding: 14px 18px;
        background: rgba(255,255,255,0.09);
        border: 1px solid rgba(255,255,255,0.25);
        border-radius: 16px;
        color: white;
        font-size: 16px;
    }
    .search-box button {
        padding: 0 28px;
        background: var(--primary);
        color: white;
        border: none;
        border-radius: 16px;
        cursor: pointer;
        font-weight: 600;
    }
    .search-box button:hover {
        background: #c026d3;
    }

    .add-btn {
        background: linear-gradient(135deg, var(--primary), var(--accent));
        color: white;
        padding: 14px 28px;
        border: none;
        border-radius: 16px;
        font-weight: 700;
        font-size: 16px;
        cursor: pointer;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 10px;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        background: rgba(255,255,255,0.06);
        border-radius: 20px;
        overflow: hidden;
        margin-top: 10px;
    }
    th, td {
        padding: 16px 20px;
        text-align: left;
        border-bottom: 1px solid rgba(255,255,255,0.12);
    }
    th {
        background: rgba(168,85,247,0.25);
        color: #e0bbff;
        font-weight: 600;
    }
    tr:hover {
        background: rgba(255,255,255,0.08);
    }
    .actions {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
    }
    .btn {
        padding: 8px 16px;
        border: none;
        border-radius: 10px;
        font-size: 14px;
        cursor: pointer;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 6px;
    }
    .btn-view { background: #3b82f6; color: white; }
    .btn-edit { background: #eab308; color: black; }
    .btn-delete { background: #ef4444; color: white; }
    
    .btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.3);
    }
    .message {
        padding: 16px 24px;
        border-radius: 16px;
        margin-bottom: 25px;
        font-weight: 600;
    }
    .success { background: rgba(34,197,94,0.25); border: 1px solid #4ade80; color: #86efac; }
    .error { background: rgba(239,68,68,0.25); border: 1px solid #f87171; color: #fca5a5; }
    .no-data {
        text-align: center;
        padding: 60px 20px;
        color: #94a3b8;
        font-size: 1.1rem;
    }
    .clear-search {
        color: #a855f7;
        text-decoration: none;
        font-size: 14px;
        margin-left: 10px;
    }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>

<div class="glass-container">
    <div class="header">
        <h1><i class="fas fa-list"></i> Planning Records</h1>
        <a href="add_planning.php" class="add-btn">
            <i class="fas fa-plus"></i> Add New Planning
        </a>
    </div>

    <div class="form-area">

        <?php if (isset($success)): ?>
            <div class="message success"><?= $success ?></div>
        <?php endif; ?>
        <?php if (isset($error)): ?>
            <div class="message error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <!-- Search Form -->
        <form method="GET" class="search-box">
            <input type="text" 
                   name="search" 
                   value="<?= htmlspecialchars($search) ?>" 
                   placeholder="Search by Project Name or Code..." 
                   autocomplete="off">
            <button type="submit"><i class="fas fa-search"></i> Search</button>
        </form>

        <?php if (!empty($search)): ?>
            <p>
                Showing results for: <strong>"<?= htmlspecialchars($search) ?>"</strong>
                <a href="planning_list.php" class="clear-search">Clear Search</a>
            </p>
        <?php endif; ?>

        <?php if ($result && $result->num_rows > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Project Name</th>
                        <th>Project Code</th>
                        <th>Budget Items</th>
                        <th>Milestones</th>
                        <th>Created On</th>
                        <th>Last Updated</th>
                        <th width="220">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $i = 1;
                    while ($row = $result->fetch_assoc()): 
                    ?>
                    <tr>
                        <td><?= $i++ ?></td>
                        <td><strong><?= htmlspecialchars($row['project_name']) ?></strong></td>
                        <td><?= htmlspecialchars($row['project_code'] ?? 'N/A') ?></td>
                        <td><?= $row['item_count'] ?> items</td>
                        <td><?= $row['milestone_count'] ?> milestones</td>
                        <td><?= date('d M Y', strtotime($row['created_at'])) ?><br>
                            <small style="opacity:0.7;"><?= date('h:i A', strtotime($row['created_at'])) ?></small>
                        </td>
                        <td>
                            <?php if ($row['updated_at']): ?>
                                <?= date('d M Y', strtotime($row['updated_at'])) ?>
                            <?php else: ?>
                                <em style="opacity:0.6;">Never</em>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="actions">
                                <a href="planning_view.php?id=<?= $row['id'] ?>" class="btn btn-view" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="planning_edit.php?id=<?= $row['id'] ?>" class="btn btn-edit" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="?delete=<?= $row['id'] ?><?= !empty($search) ? '&search='.urlencode($search) : '' ?>" 
                                   class="btn btn-delete" 
                                   title="Delete"
                                   onclick="return confirm('Are you sure you want to delete this planning record?\nThis action cannot be undone.');">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div class="no-data">
                <i class="fas fa-folder-open" style="font-size:3.5rem; margin-bottom:20px; opacity:0.5;"></i>
                <p>
                    <?php if (!empty($search)): ?>
                        No records found matching "<strong><?= htmlspecialchars($search) ?></strong>"
                    <?php else: ?>
                        No planning records found.
                    <?php endif; ?>
                </p>
                <?php if (!empty($search)): ?>
                    <a href="planning_list.php" class="add-btn" style="margin-top:20px; display:inline-block;">
                        Clear Search
                    </a>
                <?php else: ?>
                    <a href="add_planning.php" class="add-btn" style="margin-top:20px; display:inline-block;">
                        <i class="fas fa-plus"></i> Create First Planning
                    </a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
// Auto hide success message
setTimeout(() => {
    const successMsg = document.querySelector('.success');
    if (successMsg) successMsg.style.display = 'none';
}, 5000);
</script>

</body>
</html>