<?php
session_start();
$nama_pegawai = $_SESSION['nama_pegawai'];

include '../koneksi.php';
if (isset($_POST["tambah"])) {

    $idtelp_custraxi = $_POST["idtelp_custraxi"];
    // echo "<br>";
    $tgl = $_POST["tgl_customer"];
    // echo "<br>";
    $bu = $_POST["bu"];
    $nama = $_POST["bu"] . $_POST["nama_customer"];
    // echo "<br>";
    $nama_customer = $_POST["nama_customer"];
    // $pic = $_POST["tt"] . " " . $_POST["pic"];
    // echo "<br>";
    $alamat = $_POST["alamat"];
    $telpe = $_POST["telp"];
    $telp = str_replace('-', '', $telpe);
    // echo "<br>";
    // $tt = $_POST["tt"];
    $kota = $_POST["kota"];
    $email = $_POST["email"];
    $kebutuhan = $_POST["kebutuhan"];
    // echo "<br>";
    $keperluan = $_POST["keperluane"] ?? '';
    // echo "<br>";
    $status = $_POST['statuse'] ?? '';
    $tglhold = $_POST['tglhold'] ?? '';
    $note_telp = $_POST['note_telp'] ?? '';

    $sumber = $_POST["sumber"];
    // echo $keterangansumber = $_POST["keteranganSumberEmail"];

    if (empty($nama_customer)) {
        $query = mysqli_query($konek, "
            SELECT MAX(CAST(SUBSTRING(nama_customer, 5) AS UNSIGNED)) AS last_no
            FROM customer
            WHERE nama_customer LIKE 'NULL%'");
        $dataNull = mysqli_fetch_assoc($query);

        $urutan = ($dataNull['last_no'] ?? 0) + 1;

        $nama_customer = 'NULL' . $urutan;
    }

    $map = [
        'Website' => 'keteranganSumberWeb',
        'WA' => 'keteranganSumberWA',
        'Email' => 'keteranganSumberEmail',
        'Telp' => 'keteranganSumberTelp'
    ];

    if (isset($map[$sumber])) {
        echo $ketarangansumber = $_POST[$map[$sumber]] ?? '';
    } else {
        $keterangansumber = ' ';
    }

    if (str_contains(strtolower($keperluan), 'service')) {
        $jenis_keperluan = 'service';
    } else if (str_contains(strtolower($keperluan), 'rental')) {
        $jenis_keperluan = 'rental';
    }else {
        $jenis_keperluan = 'penjualan';
    }

    // if (str_contains(strtolower($keperluan), 'service')) {
        $cekcust = mysqli_query($konek, "SELECT * FROM customer WHERE nama_customer = '$nama_customer' AND alamat='$alamat' AND kota='$kota' AND bu='$bu'");
        // $jenis_keperluan = 'service';
        if ($data = mysqli_num_rows($cekcust) > 0) {
            $caricus = mysqli_query($konek, "SELECT * FROM customer WHERE nama_customer = '$nama_customer' AND alamat='$alamat' AND kota='$kota' AND bu='$bu'");
            $row = mysqli_fetch_array($caricus);
            $idcustomer = $row["idcustomer"];
        } else {
            $query = mysqli_query($konek, "
                SELECT MAX(idcustomer) AS last_id FROM customer");
            $data = mysqli_fetch_assoc($query);

            $lastId = $data['last_id'];
            $urutan = (int) substr($lastId, 3, 5);
            $urutan++;

            $idcustomer = 'CUS' . str_pad($urutan, 5, '0', STR_PAD_LEFT);
            $tglinputcustomer = date('Y-m-d');

            $sqlmasuk = mysqli_query($konek, "INSERT INTO customer VALUES ('$idcustomer','$bu','$nama_customer','$alamat','$kota','$telp','$email','$tglinputcustomer')");
        }
    // } else {
    //     $cekcust = mysqli_query($konek, "SELECT * FROM customer_penjul WHERE nama_customer = '$nama_customer' AND alamat='$alamat' AND kota='$kota' AND bu='$bu'");
    //     $jenis_keperluan = 'penjualan';
    //     if ($data = mysqli_num_rows($cekcust) > 0) {
    //         $caricus = mysqli_query($konek, "SELECT * FROM customer_penjul WHERE nama_customer = '$nama_customer' AND alamat='$alamat' AND kota='$kota' AND bu='$bu'");
    //         $row = mysqli_fetch_array($caricus);
    //         $idcustomer = $row["idcustomer"];
    //     } else {
    //         $query = mysqli_query($konek, "
    //             SELECT MAX(idcustomer) AS last_id FROM customer_penjul");
    //         $data = mysqli_fetch_assoc($query);

    //         $lastId = $data['last_id'];
    //         $urutan = (int) substr($lastId, 3, 5);
    //         $urutan++;

    //         echo $idcustomer = 'CUP' . str_pad($urutan, 5, '0', STR_PAD_LEFT);
    //         $sqlmasuk = mysqli_query($konek, "INSERT INTO customer_penjul VALUES ('$idcustomer','$bu','$nama_customer','$alamat','$kota','$telp','$email')");
    //     }
    // }

    $buatpenawaran = 0;
    $cektelp = mysqli_query($konek, "SELECT * FROM telp_custraxi WHERE idtelp_custraxi = '$idtelp_custraxi'");
    if (mysqli_num_rows($cektelp) == 0) {
        $sql = mysqli_query($konek, "INSERT INTO telp_custraxi VALUES ('$idtelp_custraxi','$tgl','$idcustomer','$keperluan','$kebutuhan','$jenis_keperluan','$sumber','$ketarangansumber','$buatpenawaran','$note_telp')");
    } else {
        $cektelp1 = mysqli_query($konek, "SELECT * FROM telp_custraxi WHERE idtelp_custraxi = '$idtelp_custraxi' AND idcustomer='$idcustomer'");
        if (mysqli_num_rows($cektelp1) == 1) {
            $idtelp_custraxi = $_POST["idtelp_custraxi"];
        } else {
            $query = mysqli_query($konek, "
            SELECT MAX(idtelp_custraxi) AS last_id FROM telp_custraxi");
            $data = mysqli_fetch_assoc($query);

            $lastId = $data['last_id']; // PGW005
            $urutan = (int) substr($lastId, 3, 5);
            $urutan++;

            echo $keterangansumber;
            $idtelp_custraxi = 'TCR' . str_pad($urutan, 5, '0', STR_PAD_LEFT);
            header("Location: ../telp_custraxitambah.php?idtelp_custraxi=$idtelp_custraxi");
            $sql = mysqli_query($konek, "INSERT INTO telp_custraxi VALUES ('$idtelp_custraxi','$tgl','$idcustomer','$keperluan','$kebutuhan','$jenis_keperluan','$sumber','$ketarangansumber','$buatpenawaran','$note_telp')");
        }
    }


    //Follow Up
    $query = mysqli_query($konek, "
                SELECT MAX(idfollowup_raxi) AS last_id FROM followup_raxi");
    $data = mysqli_fetch_assoc($query);

    $lastId = $data['last_id'];
    $urutan = (int) substr($lastId, 3, 5);
    $urutan++;

    $idfollowup_raxi = 'FTR' . str_pad($urutan, 5, '0', STR_PAD_LEFT);
    $tglfllw = date('Y-m-d');

    if ($status == "Penawaran" || $status == "Closing" || $status == "Cancel") {
        $masukfollow = mysqli_query($konek, "INSERT INTO followup_raxi VALUES('$idfollowup_raxi','$tglfllw','$status','$tglfllw','','','$idtelp_custraxi')");
    } else if ($status == 'Hold') {
        $masukfollow = mysqli_query($konek, "INSERT INTO followup_raxi VALUES('$idfollowup_raxi','$tglfllw','$status','$tglfllw','$tglhold','','$idtelp_custraxi')");
    }

    //detail telp
    $query = mysqli_query($konek, "
                SELECT MAX(iddtelp_custraxi) AS last_id FROM telp_custraxi_detail");
    $data = mysqli_fetch_assoc($query);

    $lastId = $data['last_id'];
    $urutan = (int) substr($lastId, 3, 5);
    $urutan++;

    $iddetail_raxips = 'TDR' . str_pad($urutan, 5, '0', STR_PAD_LEFT);
    // $sqle = mysqli_query($konek, "INSERT INTO telp_custraxi_detail VALUES('$iddetail_raxips','$idtelp_custraxi','$sumber','$keterangansumber')");
    header("Location: ../telp_custraxitambah.php?idtelp_custraxi=$idtelp_custraxi&modal=ModalTmbTelp");
}
if (isset($_POST['edit'])) {
    // echo "Jiahaha";
    $idtelp_custraxi = $_POST["idtelp_custraxi"];
    $tgltelp_custraxi = $_POST["tgltelp_custraxi"];
    $keperluan = $_POST["keperluane"];
    $note = $_POST["note"];
    $note_telp = $_POST["note_telp"];

    $sqledit = mysqli_query($konek, "UPDATE telp_custraxi SET tgltelp_custraxi='$tgltelp_custraxi',keperluan='$keperluan',note='$note' WHERE idtelp_custraxi='$idtelp_custraxi'");
    header("Location: ../telp_custraxi.php");
}
if (isset($_POST['tmbpic'])) {
    // echo "Jiahaha";
    echo $idtelp_custraxi = $_GET["idtelp_custraxi"];
    echo "<br>";
    echo $pic = $_POST['tt'] . " " . $_POST["pic"];
    echo "<br>";
    echo $telppice = $_POST["telppic"];
    $telppic = str_replace('-', '', $telppice);
    $note = $_POST["note"];

    $cariidcus = mysqli_query($konek, "SELECT * FROM telp_custraxi WHERE idtelp_custraxi='$idtelp_custraxi'");
    $idcustomer = mysqli_fetch_array($cariidcus);
    $idcustomer = $idcustomer["idcustomer"];

    if (strpos($idcustomer, 'CUS') === 0) {
        $cariidpice = mysqli_query($konek, "SELECT * FROM pic WHERE idcustomer='$idcustomer' AND nama_pic='$pic' AND telp_pic='$telppic'");

        $idpice = mysqli_num_rows($cariidpice);

        if ($idpice === 0) {
            $query = mysqli_query($konek, "
            SELECT MAX(idpic) AS last_id FROM pic");
            $data = mysqli_fetch_assoc($query);

            $lastId = $data['last_id']; // PGW005
            $urutan = (int) substr($lastId, 3, 5);
            $urutan++;

            $idpic = 'PIC' . str_pad($urutan, 5, '0', STR_PAD_LEFT);

            //CEK PIC LALU CUSTOMER
            if (empty($_POST["pic"])) {
                $masukpic = mysqli_query($konek, "INSERT INTO pic VALUES('$idpic','$idcustomer','$telppic','$telppic','$note')");
                }else{
                $masukpic = mysqli_query($konek, "INSERT INTO pic VALUES('$idpic','$idcustomer','$pic','$telppic','$note')");
            }

        } else {
            $cariidpic = mysqli_query($konek, "SELECT * FROM pic WHERE idcustomer='$idcustomer' AND nama_pic='$pic' AND telp_pic='$telppic'");
            $idpic = mysqli_fetch_assoc($cariidpic);
            echo $idpic = $idpic["idpic"] ?? '';
        }
        $query = mysqli_query($konek, "
            SELECT MAX(iddtelp_custraxi) AS last_id FROM telp_custraxi_detail");
        $data = mysqli_fetch_assoc($query);

        $lastId = $data['last_id']; // PGW005
        $urutan = (int) substr($lastId, 3, 5);
        $urutan++;

        $iddtelp_custraxi = 'TDR' . str_pad($urutan, 5, '0', STR_PAD_LEFT);

        $masukdtelp = mysqli_query($konek, "INSERT INTO telp_custraxi_detail VALUES('$iddtelp_custraxi','$idtelp_custraxi','$idpic')");
    } else {
        $cariidpice = mysqli_query($konek, "SELECT * FROM pic_penjul WHERE idcustomer='$idcustomer' AND nama_pic='$pic' AND telp_pic='$telppic'");

        $idpice = mysqli_num_rows($cariidpice);

        if ($idpice === 0) {
            $query = mysqli_query($konek, "
            SELECT MAX(idpic) AS last_id FROM pic_penjul");
            $data = mysqli_fetch_assoc($query);

            $lastId = $data['last_id']; // PGW005
            $urutan = (int) substr($lastId, 3, 5);
            $urutan++;

            $idpic = 'PIC' . str_pad($urutan, 5, '0', STR_PAD_LEFT);

            $masukpic = mysqli_query($konek, "INSERT INTO pic_penjul VALUES('$idpic','$idcustomer','$pic','$telppic','$note')");
        } else {
            $cariidpic = mysqli_query($konek, "SELECT * FROM pic_penjul WHERE idcustomer='$idcustomer' AND nama_pic='$pic' AND telp_pic='$telppic'");
            $idpic = mysqli_fetch_assoc($cariidpic);
            echo $idpic = $idpic["idpic"] ?? '';
        }
        $query = mysqli_query($konek, "
            SELECT MAX(iddtelp_custraxi) AS last_id FROM telp_custraxi_detail");
        $data = mysqli_fetch_assoc($query);

        $lastId = $data['last_id']; // PGW005
        $urutan = (int) substr($lastId, 3, 5);
        $urutan++;

        $iddtelp_custraxi = 'TDR' . str_pad($urutan, 5, '0', STR_PAD_LEFT);

        $masukdtelp = mysqli_query($konek, "INSERT INTO telp_custraxi_detail VALUES('$iddtelp_custraxi','$idtelp_custraxi','$idpic')");
    }

    // $sqledit = mysqli_query($konek, "UPDATE telp_custraxi SET tgltelp_custraxi='$tgltelp_custraxi',keperluan='$keperluan',note='$note' WHERE idtelp_custraxi='$idtelp_custraxi'");
    // header("Location: ../telp_custraxi.php");
    if (isset($_GET['uedit'])) {
        header("Location: ../telp_custraxiedit.php?idtelp_custraxi=$idtelp_custraxi");
    } else {
        header("Location: ../telp_custraxitambah.php?idtelp_custraxi=$idtelp_custraxi");
    }
}
if (isset($_GET['hps'])) {
    $iddtelp_custraxi = $_GET['iddtelp_custraxi'];
    $idtelp_custraxi = $_GET['idtelp_custraxi'];

    $hps = mysqli_query($konek, "DELETE FROM telp_custraxi_detail WHERE iddtelp_custraxi = '$iddtelp_custraxi'");
    if (isset($_GET['uedit'])) {
        header("Location: ../telp_custraxiedit.php?idtelp_custraxi=$idtelp_custraxi");
    } else {
        header("Location: ../telp_custraxitambah.php?idtelp_custraxi=$idtelp_custraxi");
    }
}
if (isset($_POST['editpic'])) {
    $idtelp_custraxi = $_POST['idtelp_custraxi'];
    echo $idpic = $_POST['idpic'];
    echo $pic = $_POST['tt'] . " " . $_POST['pic'];
    // echo $telp = $_POST['telp'];
    $telp = $_POST["telp"];
    $telp = str_replace('-', '', $telp);
    $note = $_POST["note"];

    $editpic = mysqli_query($konek, "UPDATE pic SET nama_pic='$pic',telp_pic='$telp',note = '$note' WHERE idpic = '$idpic'");
    header("Location: ../telp_custraxiedit.php?idtelp_custraxi=$idtelp_custraxi");
}
if (isset($_POST['selesaiedit'])) {
    $idtelp_custraxi = $_POST["idtelp_custraxi"];
    $email = $_POST["email"];
    echo "<br>";
    $keperluan = $_POST["keperluane"] ?? '';
    echo "<br>";
    $note = $_POST["note"];
    $note_telp = $_POST["note_telp"];
    echo $sumber = $_POST["sumber"];

    $map = [
        'Website' => 'keteranganSumberWeb',
        'WA' => 'keteranganSumberWA',
        'Email' => 'keteranganSumberEmail',
        'Telp' => 'keteranganSumberTelp'
    ];

    if (isset($map[$sumber])) {
        echo $ketarangansumber = $_POST[$map[$sumber]] ?? '';
    } else {
        $keterangansumber = '';
    }

    $edittelp = mysqli_query($konek, "UPDATE telp_custraxi SET keperluan='$keperluan',sumber='$sumber',ket_sumber='$ketarangansumber',note_telp='$note_telp' WHERE idtelp_custraxi = '$idtelp_custraxi'");
    header("Location: ../telp_custraxi.php");
}
if (isset($_GET['hpstelp'])) {
    $idtelp_custraxi = $_GET['idtelp_custraxi'];
    $tgl = $_GET['tgl'];

    $hps = mysqli_query($konek, "DELETE FROM followup_raxi WHERE idtelp_custraxi = '$idtelp_custraxi'");
    $hps = mysqli_query($konek, "DELETE FROM telp_custraxi_detail WHERE idtelp_custraxi = '$idtelp_custraxi'");
    $hps = mysqli_query($konek, "DELETE FROM telp_custraxi WHERE idtelp_custraxi = '$idtelp_custraxi'");
    header("Location: ../telp_custraxi.php");
}
if (isset($_POST['fllwup'])) {
    // echo $tgl = date('Y-m-d');
    // echo "<br>";
    echo $idtelp_custraxi = $_POST['idtelp_custraxi'];
    echo "<br>";
    echo $picada = $_POST['picada'];
    echo "<br>";
    echo $sttsfollowup = $_POST['sttsfollowup'];
    echo "<br>";
    echo $tglhold = $_POST['tglhold'];
    echo "<br>";
    echo $notefllw = $_POST['notefllw'];
    echo "<br>";
    $tgle = date('Y-m-d');
    $query = mysqli_query($konek, "
                SELECT MAX(idfollowup_raxi) AS last_id FROM followup_raxi");
    $data = mysqli_fetch_assoc($query);

    $lastId = $data['last_id'];
    $urutan = (int) substr($lastId, 3, 5);
    $urutan++;

    $idfollowup_raxi = 'FTR' . str_pad($urutan, 5, '0', STR_PAD_LEFT);
    if ($picada == 'ada') {
        $tglfllw = date('Y-m-d');
    } else {
        $cari = mysqli_query($konek, "SELECT * FROM followup_raxi WHERE idtelp_custraxi = '$idtelp_custraxi' AND idfollowup_raxi < '$idfollowup_raxi' ORDER BY idfollowup_raxi DESC LIMIT 1");
        $caris = mysqli_fetch_assoc($cari);
        $tglfllw = $caris["tglraxi_followup"];
    }
    $query = mysqli_query($konek, "INSERT INTO followup_raxi VALUES ('$idfollowup_raxi','$tgle','$sttsfollowup','$tglfllw','$tglhold','$notefllw','$idtelp_custraxi')");
    header("Location: ../telp_custraxi.php");
}
if (isset($_POST['buatpen'])) {
    echo $idtelp_custraxi = $_GET['idtelp_custraxi'];
    echo "<br>";
    echo $jpenawaran = $_POST['radiopen'];
    echo "<br>";
    echo $kota = $_POST['radiokot'];
    echo "<br>";

    if ($jpenawaran == "Penawaran Service") {
        header("Location: ../asset/autoid-penawaranraxi.php?radiokota=$kota&idtelp_custraxi=$idtelp_custraxi");
    } else {
        echo "<script>
            alert('Maaf!! Fitur ini masih dalam pengembangan!');
            window.location='../telp_custraxi.php';
          </script>";
    }
}
