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

// Allowed Roles
$allowed_roles = ['store manager', 'admin', 'project manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: ../login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$success = "";
$error = "";

// Fetch Projects & UOMs
$projects = $conn->query("SELECT id, project_code, project_name FROM project_master WHERE project_status IN ('Active', 'In Progress') ORDER BY project_name ASC");
$uoms_result = $conn->query("SELECT id, uom_name FROM uom_tbl ORDER BY uom_name ASC");
$uoms = $uoms_result->fetch_all(MYSQLI_ASSOC);

// ========================== FORM SUBMISSION ==========================
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $report_date = $_POST['report_date'] ?? date('Y-m-d');
    $project_id  = (int)($_POST['project_id'] ?? 0);

    try {
        $conn->begin_transaction();

        // Insert DPR Master
        $stmt = $conn->prepare("INSERT INTO dpr_master (report_date, project_id, created_by, created_at) 
                               VALUES (?, ?, ?, NOW())");
        $stmt->bind_param("sii", $report_date, $project_id, $user_id);
        $stmt->execute();
        $dpr_id = $conn->insert_id;

        // ====================== PROGRESS REPORT ======================
        if (!empty($_POST['progress'])) {
            $prog_stmt = $conn->prepare("INSERT INTO dpr_progress 
                (dpr_id, sr_no, activities, uom_id, scope_qty, clear_scope, completed_till_previous_day, 
                 achieved_for_the_day, achieved_upto_date, balance, remarks) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

            foreach ($_POST['progress'] as $p) {
                $sr_no = (int)($p['sr_no'] ?? 0);
                $activities = trim($p['activities'] ?? '');
                $uom_id = !empty($p['uom']) ? (int)$p['uom'] : null;
                $scope = (float)($p['scope'] ?? 0);
                $clear_scope = (float)($p['clear_scope'] ?? 0);
                $prev = (float)($p['completed_till_previous_day'] ?? 0);
                $today = (float)($p['achieved_for_the_day'] ?? 0);
                $upto = (float)($p['achieved_upto_date'] ?? 0);
                $balance = (float)($p['balance'] ?? 0);
                $remarks = trim($p['remarks'] ?? '');

                $prog_stmt->bind_param("iisidddddds", $dpr_id, $sr_no, $activities, $uom_id, 
                                       $scope, $clear_scope, $prev, $today, $upto, $balance, $remarks);
                $prog_stmt->execute();
            }
        }

        // ====================== MAJOR MATERIAL ======================
        if (!empty($_POST['majormaterial'])) {
            $mat_stmt = $conn->prepare("INSERT INTO dpr_major_material 
                (dpr_id, sr_no, description, uom_id, quantity) VALUES (?, ?, ?, ?, ?)");

            foreach ($_POST['majormaterial'] as $m) {
                $sr_no = (int)($m['sr_no'] ?? 0);
                $desc = trim($m['description'] ?? '');
                $uom_id = !empty($m['uom']) ? (int)$m['uom'] : null;
                $qty = (float)($m['quantity'] ?? 0);

                $mat_stmt->bind_param("iisid", $dpr_id, $sr_no, $desc, $uom_id, $qty);
                $mat_stmt->execute();
            }
        }

        // ====================== CRITICAL ISSUES ======================
        if (!empty($_POST['criticalissue'])) {
            $issue_stmt = $conn->prepare("INSERT INTO dpr_critical_issues 
                (dpr_id, sr_no, description) VALUES (?, ?, ?)");

            foreach ($_POST['criticalissue'] as $c) {
                $sr_no = (int)($c['sr_no'] ?? 0);
                $desc = trim($c['description'] ?? '');

                $issue_stmt->bind_param("iis", $dpr_id, $sr_no, $desc);
                $issue_stmt->execute();
            }
        }

        // ====================== MANPOWER ======================
        if (!empty($_POST['manpower'])) {
            $man_stmt = $conn->prepare("INSERT INTO dpr_manpower 
                (dpr_id, sr_no, description, no_of_manpower) VALUES (?, ?, ?, ?)");

            foreach ($_POST['manpower'] as $m) {
                $sr_no = (int)($m['sr_no'] ?? 0);
                $desc = trim($m['description'] ?? '');
                $count = (int)($m['no_of_manpower'] ?? 0);

                $man_stmt->bind_param("iisi", $dpr_id, $sr_no, $desc, $count);
                $man_stmt->execute();
            }
        }

        $conn->commit();
        $success = "Daily Progress Report saved successfully!";

    } catch (Exception $e) {
        $conn->rollback();
        $error = "Error: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Daily Progress Report</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;
        background: linear-gradient(135deg, rgba(0, 0, 0, 0.78), rgba(0, 0, 0, 0.92)), url('../background.jpeg') center/cover fixed;
        color: #f1f5f9;
        padding: 20px 15px;
    }

    .container {
        max-width: 1350px;
        margin: auto;
    }

    .glass-container {
        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: 45px 40px;
        text-align: center;
    }

    .header h1 {
        font-size: 2.5rem;
        font-weight: 700;
    }

    .form-area {
        padding: 40px;
    }

    .section {
        background: rgba(255, 255, 255, 0.07);
        border: 1px solid rgba(255, 255, 255, 0.18);
        border-radius: 20px;
        padding: 28px;
        margin-bottom: 30px;
    }

    label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        color: #e0e7ff;
    }

    input,
    select,
    textarea {
        width: 100%;
        padding: 14px 16px;
        background: rgba(255, 255, 255, 0.09);
        border: 1px solid rgba(255, 255, 255, 0.25);
        border-radius: 12px;
        color: white;
        font-size: 15px;
    }

    input:focus,
    select:focus,
    textarea:focus {
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(168, 85, 247, 0.25);
    }

    .dynamic-row {
        background: rgba(0, 0, 0, 0.25);
        padding: 20px;
        border-radius: 16px;
        margin-bottom: 18px;
        position: relative;
    }

    .remove-btn {
        position: absolute;
        top: 12px;
        right: 12px;
        background: #ef4444;
        color: white;
        border: none;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        cursor: pointer;
        font-size: 18px;
    }

    .add-row-btn,
    .submit-btn {
        width: 100%;
        padding: 18px;
        border-radius: 16px;
        font-weight: 700;
        font-size: 17px;
        cursor: pointer;
        margin: 20px 0;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
    }

    .add-row-btn {
        background: rgba(168, 85, 247, 0.2);
        color: #c4b5fd;
        border: 1px solid rgba(168, 85, 247, 0.4);
    }

    .submit-btn {
        background: linear-gradient(135deg, var(--primary), var(--accent));
        color: white;
        border: none;
    }

    .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;
    }

    @media (max-width: 768px) {
        .header h1 {
            font-size: 2rem;
        }

        .form-area {
            padding: 25px 18px;
        }
    }
    </style>
</head>

<body>
    <?php include('../config/header.php'); ?>
    <div class="container">
        <div class="glass-container">
            <div class="header">
                <a href="dpr_list.php" style="color:#c4b5fd; text-decoration:none; float:left; font-size:1.1rem;">
                    ← Back to DPR List
                </a>
                <h1><i class="fas fa-calendar-plus"></i> Add Daily Progress Report (DPR)</h1>
            </div>

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

                <form method="post" id="dprForm">

                    <div class="section">
                        <label>Project *</label>
                        <select name="project_id" required>
                            <option value="">-- Select Project --</option>
                            <?php while ($p = $projects->fetch_assoc()): ?>
                            <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['project_code']) ?> -
                                <?= htmlspecialchars($p['project_name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>

                    <div class="section">
                        <label>Report Date *</label>
                        <input type="date" name="report_date" value="<?= date('Y-m-d') ?>" required>
                    </div>

                    <!-- Progress Report -->
                    <div class="section">
                        <h2>1. Progress Report</h2>
                        <div id="progressContainer"></div>
                        <div class="add-row-btn" onclick="addNewProgressRow()">
                            <i class="fas fa-plus-circle"></i> Add Progress Row
                        </div>
                    </div>

                    <!-- Major Material -->
                    <div class="section">
                        <h2>2. Major Materials Used</h2>
                        <div id="majorMaterialContainer"></div>
                        <div class="add-row-btn" onclick="addNewMajorMaterialRow()">
                            <i class="fas fa-plus-circle"></i> Add Material
                        </div>
                    </div>

                    <!-- Critical Issues -->
                    <div class="section">
                        <h2>3. Critical Issues / Delays</h2>
                        <div id="criticalIssueContainer"></div>
                        <div class="add-row-btn" onclick="addNewCriticalIssueRow()">
                            <i class="fas fa-plus-circle"></i> Add Issue
                        </div>
                    </div>

                    <!-- Manpower -->
                    <div class="section">
                        <h2>4. Manpower Deployed</h2>
                        <div id="manpowerContainer"></div>
                        <div class="add-row-btn" onclick="addNewManpowerRow()">
                            <i class="fas fa-plus-circle"></i> Add Manpower
                        </div>
                    </div>

                    <button type="submit" class="submit-btn">
                        <i class="fas fa-save"></i> Save Daily Progress Report
                    </button>
                </form>
            </div>
        </div>
    </div>

    <script>
    let progressCount = 0,
        majorCount = 0,
        criticalCount = 0,
        manpowerCount = 0;
    const uoms = <?= json_encode($uoms) ?>;

    function addNewProgressRow() {
        progressCount++;
        const html = `
        <div class="dynamic-row" id="prog-${progressCount}">
            <button type="button" class="remove-btn" onclick="this.parentElement.remove()">×</button>
            <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(200px,1fr)); gap:15px;">
                <div><label>Sr No</label><input type="number" name="progress[${progressCount}][sr_no]" value="${progressCount}" readonly></div>
                <div><label>Activities</label><textarea name="progress[${progressCount}][activities]" rows="2" placeholder="Enter activity..."></textarea></div>
                <div><label>UOM</label><select name="progress[${progressCount}][uom]">${uoms.map(u => `<option value="${u.id}">${u.uom_name}</option>`).join('')}</select></div>
                <div><label>Scope Qty</label><input type="number" step="0.01" name="progress[${progressCount}][scope]"></div>
                <div><label>Clear Scope</label><input type="number" step="0.01" name="progress[${progressCount}][clear_scope]"></div>
                <div><label>Completed Till Previous Day</label><input type="number" step="0.01" name="progress[${progressCount}][completed_till_previous_day]"></div>
                <div><label>Achieved For The Day</label><input type="number" step="0.01" name="progress[${progressCount}][achieved_for_the_day]"></div>
                <div><label>Achieved Upto Date</label><input type="number" step="0.01" name="progress[${progressCount}][achieved_upto_date]"></div>
                <div><label>Balance</label><input type="number" step="0.01" name="progress[${progressCount}][balance]"></div>
                <div><label>Remarks</label><textarea name="progress[${progressCount}][remarks]" rows="2"></textarea></div>
            </div>
        </div>`;
        document.getElementById('progressContainer').insertAdjacentHTML('beforeend', html);
    }

    function addNewMajorMaterialRow() {
        majorCount++;
        const html = `
        <div class="dynamic-row" id="major-${majorCount}">
            <button type="button" class="remove-btn" onclick="this.parentElement.remove()">×</button>
            <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(200px,1fr)); gap:15px;">
                <div><label>Sr No</label><input type="number" name="majormaterial[${majorCount}][sr_no]" value="${majorCount}" readonly></div>
                <div><label>Description</label><textarea name="majormaterial[${majorCount}][description]" rows="2"></textarea></div>
                <div><label>UOM</label><select name="majormaterial[${majorCount}][uom]">${uoms.map(u => `<option value="${u.id}">${u.uom_name}</option>`).join('')}</select></div>
                <div><label>Quantity</label><input type="number" step="0.01" name="majormaterial[${majorCount}][quantity]"></div>
            </div>
        </div>`;
        document.getElementById('majorMaterialContainer').insertAdjacentHTML('beforeend', html);
    }

    function addNewCriticalIssueRow() {
        criticalCount++;
        const html = `
        <div class="dynamic-row" id="crit-${criticalCount}">
            <button type="button" class="remove-btn" onclick="this.parentElement.remove()">×</button>
            <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(200px,1fr)); gap:15px;">
                <div><label>Sr No</label><input type="number" name="criticalissue[${criticalCount}][sr_no]" value="${criticalCount}" readonly></div>
                <div><label>Description</label><textarea name="criticalissue[${criticalCount}][description]" rows="3"></textarea></div>
            </div>
        </div>`;
        document.getElementById('criticalIssueContainer').insertAdjacentHTML('beforeend', html);
    }

    function addNewManpowerRow() {
        manpowerCount++;
        const html = `
        <div class="dynamic-row" id="man-${manpowerCount}">
            <button type="button" class="remove-btn" onclick="this.parentElement.remove()">×</button>
            <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(200px,1fr)); gap:15px;">
                <div><label>Sr No</label><input type="number" name="manpower[${manpowerCount}][sr_no]" value="${manpowerCount}" readonly></div>
                <div><label>Description</label><textarea name="manpower[${manpowerCount}][description]" rows="2"></textarea></div>
                <div><label>No. of Manpower</label><input type="number" name="manpower[${manpowerCount}][no_of_manpower]"></div>
            </div>
        </div>`;
        document.getElementById('manpowerContainer').insertAdjacentHTML('beforeend', html);
    }

    window.onload = () => {
        addNewProgressRow();
        addNewMajorMaterialRow();
        addNewCriticalIssueRow();
        addNewManpowerRow();
    };
    </script>

</body>

</html>

<?php $conn->close(); ?>