<?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");

$planning_id = (int)($_GET['id'] ?? 0);

if ($planning_id <= 0) {
    die("<h2 style='color:red;text-align:center;margin-top:50px;'>Invalid Planning ID</h2>");
}

// Fetch Planning Master
$stmt = $conn->prepare("SELECT p.*, pr.project_name, pr.project_code 
                        FROM planning_master p 
                        JOIN project_master pr ON p.project_id = pr.id 
                        WHERE p.id = ?");
$stmt->bind_param("i", $planning_id);
$stmt->execute();
$planning = $stmt->get_result()->fetch_assoc();

if (!$planning) {
    die("<h2 style='color:red;text-align:center;margin-top:50px;'>Planning record not found!</h2>");
}

// Fetch Budget Items
$budget_result = $conn->query("SELECT * FROM planning_budget 
                               WHERE planning_id = $planning_id ORDER BY id ASC");
$budget_items = $budget_result->fetch_all(MYSQLI_ASSOC);

// Fetch Schedule Items
$schedule_result = $conn->query("SELECT * FROM planning_schedule 
                                 WHERE planning_id = $planning_id ORDER BY id ASC");
$schedule_items = $schedule_result->fetch_all(MYSQLI_ASSOC);

// Fetch UOMs for display
$uom_result = $conn->query("SELECT id, uom_name FROM uom_tbl");
$uoms = [];
while ($row = $uom_result->fetch_assoc()) {
    $uoms[$row['id']] = $row['uom_name'];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Planning #<?= $planning_id ?></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;
    }
    .header h1 {
        font-size: clamp(32px, 6vw, 44px);
        font-weight: 700;
        background: linear-gradient(to right, #e0bbff, #c084fc);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    .form-area { padding: 45px 40px; }
    .section {
        background: rgba(255,255,255,0.07);
        border: 1px solid rgba(255,255,255,0.18);
        border-radius: 20px;
        padding: 32px;
        margin-bottom: 35px;
    }
    .info-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }
    .info-item label {
        font-weight: 600;
        color: #c4d0ff;
        display: block;
        margin-bottom: 5px;
        font-size: 0.95rem;
    }
    .info-item p {
        background: rgba(255,255,255,0.08);
        padding: 12px 16px;
        border-radius: 12px;
        font-size: 1.05rem;
    }
    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 15px;
        background: rgba(255,255,255,0.05);
        border-radius: 16px;
        overflow: hidden;
    }
    th, td {
        padding: 14px 16px;
        text-align: left;
        border-bottom: 1px solid rgba(255,255,255,0.1);
    }
    th {
        background: rgba(168,85,247,0.2);
        color: #e0bbff;
        font-weight: 600;
    }
    tr:last-child td { border-bottom: none; }
    .totals-box {
        background: linear-gradient(135deg, rgba(168,85,247,0.15), rgba(192,132,252,0.12));
        border: 1px solid var(--accent);
        border-radius: 20px;
        padding: 28px;
        margin: 30px 0;
    }
    .total-row {
        display: flex;
        justify-content: space-between;
        padding: 14px 0;
        font-size: 1.2rem;
        border-bottom: 1px solid rgba(255,255,255,0.15);
    }
    .total-row strong { color: #c084fc; }
    .btn {
        padding: 12px 24px;
        border: none;
        border-radius: 12px;
        font-weight: 600;
        cursor: pointer;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        margin-right: 10px;
    }
    .btn-edit { background: #a855f7; color: white; }
    .btn-back { background: rgba(255,255,255,0.15); color: white; }
    .message {
        padding: 16px 24px;
        border-radius: 16px;
        margin-bottom: 25px;
        font-weight: 600;
    }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>

<div class="glass-container">
    <div class="header">
        <h1><i class="fas fa-eye"></i> View Planning #<?= $planning_id ?></h1>
    </div>

    <div class="form-area">

        <div class="section">
            <h2><i class="fas fa-building"></i> Project Information</h2>
            <div class="info-grid">
                <div class="info-item">
                    <label>Project Name</label>
                    <p><?= htmlspecialchars($planning['project_name']) ?></p>
                </div>
                <div class="info-item">
                    <label>Project Code</label>
                    <p><?= htmlspecialchars($planning['project_code'] ?? 'N/A') ?></p>
                </div>
                <div class="info-item">
                    <label>Created At</label>
                    <p><?= date('d M Y h:i A', strtotime($planning['created_at'])) ?></p>
                </div>
                <?php if (!empty($planning['updated_at'])): ?>
                <div class="info-item">
                    <label>Last Updated</label>
                    <p><?= date('d M Y h:i A', strtotime($planning['updated_at'])) ?></p>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Budget Section -->
        <div class="section">
            <h2><i class="fas fa-money-bill-wave"></i> Budget Details</h2>
            
            <?php if (empty($budget_items)): ?>
                <p style="color:#94a3b8; font-style:italic;">No budget items added.</p>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>BBU Item No</th>
                            <th>Material Name</th>
                            <th>Quantity</th>
                            <th>UOM</th>
                            <th>Type</th>
                            <th>Rate</th>
                            <th>Amount</th>
                            <th>GST (%)</th>
                            <th>Description</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $basicTotal = 0;
                        $gstTotal = 0;
                        foreach ($budget_items as $item): 
                            $uom_name = $uoms[$item['uom']] ?? 'N/A';
                            $rowBasic = 0;
                            $gstPercent = ($item['cgst'] + $item['sgst'] + $item['igst']);

                            if ($item['type'] === 'SITC') {
                                $rowBasic = $item['sitc_amount'];
                                $rateDisplay = "₹ " . number_format($item['sitc_rate'], 2);
                                $amountDisplay = "₹ " . number_format($item['sitc_amount'], 2);
                            } else {
                                $rowBasic = $item['supply_amount'] + $item['itc_amount'];
                                $rateDisplay = "S: ₹" . number_format($item['supply_rate'],2) . "<br>ITC: ₹" . number_format($item['itc_rate'],2);
                                $amountDisplay = "S: ₹" . number_format($item['supply_amount'],2) . "<br>ITC: ₹" . number_format($item['itc_amount'],2);
                            }

                            $rowGst = $rowBasic * ($gstPercent / 100);
                            $basicTotal += $rowBasic;
                            $gstTotal += $rowGst;
                        ?>
                        <tr>
                            <td><?= htmlspecialchars($item['bbu_item_no']) ?></td>
                            <td><?= htmlspecialchars($item['name']) ?></td>
                            <td><?= number_format($item['quantity'], 3) ?></td>
                            <td><?= htmlspecialchars($uom_name) ?></td>
                            <td><strong><?= htmlspecialchars($item['type']) ?></strong></td>
                            <td><?= $rateDisplay ?></td>
                            <td><?= $amountDisplay ?></td>
                            <td><?= $gstPercent ?>%</td>
                            <td><?= htmlspecialchars($item['description'] ?? '') ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <div class="totals-box">
                    <div class="total-row"><span>Basic Total:</span> <span>₹ <?= number_format($basicTotal, 2) ?></span></div>
                    <div class="total-row"><span>GST Total:</span> <span>₹ <?= number_format($gstTotal, 2) ?></span></div>
                    <div class="total-row"><span><strong>Grand Total:</strong></span> 
                        <span><strong>₹ <?= number_format($basicTotal + $gstTotal, 2) ?></strong></span>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Schedule Section -->
        <div class="section">
            <h2><i class="fas fa-calendar-alt"></i> Schedule / Milestones</h2>
            
            <?php if (empty($schedule_items)): ?>
                <p style="color:#94a3b8; font-style:italic;">No schedule milestones added.</p>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>Milestone</th>
                            <th>Start Date</th>
                            <th>End Date</th>
                            <th>UOM</th>
                            <th>Remarks</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($schedule_items as $sch): ?>
                        <tr>
                            <td><?= htmlspecialchars($sch['milestone']) ?></td>
                            <td><?= $sch['start_date'] ? date('d M Y', strtotime($sch['start_date'])) : 'N/A' ?></td>
                            <td><?= $sch['end_date'] ? date('d M Y', strtotime($sch['end_date'])) : 'N/A' ?></td>
                            <td><?= $uoms[$sch['uom']] ?? 'N/A' ?></td>
                            <td><?= htmlspecialchars($sch['remarks'] ?? '') ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

        <div style="text-align:center; margin-top: 30px;">
            <a href="planning_edit.php?id=<?= $planning_id ?>" class="btn btn-edit">
                <i class="fas fa-edit"></i> Edit This Planning
            </a>
            <a href="planning_list.php" class="btn btn-back">
                <i class="fas fa-arrow-left"></i> Back to List
            </a>
        </div>

    </div>
</div>

</body>
</html>